hdu 1845(最大匹配)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1845

思路:匈牙利算法应用,900ms+险过。(好像直接n/2就行)

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<vector>
 6 using namespace std;
 7 #define MAXN 5555
 8 vector<int>map[MAXN];
 9 int n,m,ans;
10 bool mark[MAXN];
11 int lx[MAXN],ly[MAXN];
12 
13 int dfs(int u){
14    for(int i=0;i<map[u].size();i++){
15       int v=map[u][i];
16       if(!mark[v]){
17          mark[v]=true;
18          if(ly[v]==-1||dfs(ly[v])){
19             ly[v]=u;
20             lx[u]=v;
21             return 1;
22          }
23       }
24    }
25    return 0;
26 }
27 
28 
29 int main(){
30  //  freopen("1.txt","r",stdin);
31    int _case,u,v;
32    scanf("%d",&_case);
33    while(_case--){
34       scanf("%d",&n);m=n*3/2;ans=0;
35       for(int i=1;i<=n;i++)map[i].clear();
36       for(int i=1;i<=m;i++){
37          scanf("%d%d",&u,&v);
38          map[u].push_back(v);
39          map[v].push_back(u);
40       }
41       memset(lx,-1,(n+2)*sizeof(lx[0]));
42       memset(ly,-1,(n+2)*sizeof(ly[0]));
43       for(int i=1;i<=n;i++){
44          if(lx[i]==-1){
45             memset(mark,false,(n+2)*sizeof(mark[0]));
46             ans+=dfs(i);
47          }
48       }
49       printf("%d\n",ans/2);
50    }
51    return 0;
52 }
View Code

 

 

posted @ 2013-06-05 15:11  ihge2k  阅读(390)  评论(0编辑  收藏  举报