hdu 1845 Jimmy’s Assignment (二分匹配)
2016-10-11 21:39
501 查看
Problem Description
Jimmy is studying Advanced Graph Algorithms at his university. His most recent assignment is to find a maximum matching in a special kind of graph. This graph is undirected, has N vertices and each vertex has degree 3. Furthermore, the graphis 2-edge-connected (that is, at least 2 edges need to be removed in order to make the graph disconnected). A matching is a subset of the graph’s edges, such that no two edges in the subset have a common vertex. A maximum matching is a matching having the
maximum cardinality.
Given a series of instances of the special graph mentioned above, find the cardinality of a maximum matching for each instance.
Input
The first line of input contains an integer number T, representing the number of graph descriptions to follow. Each description contains on the first line an even integer number N (4<=N<=5000), representing the number of vertices. Each ofthe next 3*N/2 lines contains two integers A and B, separated by one blank, denoting that there is an edge between vertex A and vertex B. The vertices are numbered from 1 to N. No edge may appear twice in the input.
Output
For each of the T graphs, in the order given in the input, print one line containing the cardinality of a maximum matching.Sample Input
2 4 1 2 1 3 1 4 2 3 2 4 3 4 4 1 2 1 3 1 4 2 3 2 4 3 4
Sample Output
2 2
题意:求最大匹配的边数,每个顶点最多只能用一次。
思路:用邻接表存数据,然后二分匹配,由于是双向建图,所以得出的结果要除以2;
注意:很卡时间,while 比 for 循环快,所以尽可能的用while
;
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=5005;
struct node{
int now,next;
}str[N*3];
int n,len;
int head
,vis
,link
;
void add(int a,int b)
{
str[len].now=b;
str[len].next=head[a];
head[a]=len++;
}
int find(int u)
{
for(int i=head[u];i!=-1;i=str[i].next)
{
int v=str[i].now;
if(!vis[v])
{
vis[v]=1;
if(!link[v]||find(link[v]))
{
link[v]=u;
return 1;
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
memset(head,-1,sizeof(head));
memset(link,0,sizeof(link));
int k=(3*n)/2;
len=0;
while(k--) //这里必须用while,不然会超时;
{
int a,b;
scanf("%d%d",&a,&b);
add(a,b);
add(b,a);
}
int s=0;
for(int i=1;i<=n;i++)
{
memset(vis,0,sizeof(vis));
s+=find(i);
}
printf("%d\n",s/2);
}
}
相关文章推荐
- HDU - 1845 Jimmy’s Assignment (二分匹配)
- HDU1845 Jimmy’s Assignment 984ms 飘过啊 汗死 二分匹配最大匹配数
- HDU 1845 Jimmy’s Assignment(二分匹配)
- hdu 1845 Jimmy’s Assignment 二分匹配最小点集覆盖
- HDU 1845 Jimmy’s Assignment【二分匹配,三正则图】
- hdu1845 Jimmy’s Assignment --- 完备匹配
- 二分匹配续(hdu 1845,hdu 2063)
- HDU-1281(二分匹配_必要边)
- hdu 3861 The King’s Problem 强联通+二分匹配
- 伤不起的 强连通+二分匹配 hdu 3861
- HDU-1150(求最小覆盖顶点数=二分最大匹配数)
- hdu 1507 二分匹配
- HDU1281-棋盘游戏-二分匹配与增广链
- hdu1083——二分匹配
- hdu 2444 The Accomodation of Students 二分匹配
- HDU-2063(简单二分匹配)
- hdu 无题II 二分+枚举+最大匹配
- hdu 2063 过山车 基础最大二分匹配
- HDU 4185 Oil Skimming(二分匹配,匈牙利算法)
- HDU 1045 Fire Net(建模,用二分匹配)