1. 程式人生 > 實用技巧 >hdu2444 The Accomodation of Students

hdu2444 The Accomodation of Students

http://acm.hdu.edu.cn/showproblem.php?pid=2444

Problem Description There are a group of students. Some of them may know each other, while others don't. For example, A and B know each other, B and C know each other. But this may not imply that A and C know each other.
Now you are given all pairs of students who know each other. Your task is to divide the students into two groups so that any two students in the same group don't know each other.If this goal can be achieved, then arrange them into double rooms. Remember, only paris appearing in the previous given set can live in the same room, which means only known students can live in the same room.
Calculate the maximum number of pairs that can be arranged into these double rooms. Input For each data set:
The first line gives two integers, n and m(1<n<=200), indicating there are n students and m pairs of students who know each other. The next m lines give such pairs.
Proceed to the end of file.

Output If these students cannot be divided into two groups, print "No". Otherwise, print the maximum number of pairs that can be arranged in those rooms.

題意:給你一張圖,你需要先判斷這個圖是不是二分圖,然後在求其的最大匹配。

#include <bits/stdc++.h>
using namespace std;

const int MAXN=200+5;
vector<int> G[MAXN];
int uN, linker[MAXN];
bool used[MAXN]; bool dfs(int u){ for(int i=0; i<G[u].size(); i++){ int v=G[u][i]; if(!used[v]){ used[v]=true; if(linker[v]==-1 || dfs(linker[v])){ linker[v]=u; return true; } } } return false; } int hungary(){ int res=0; memset(linker, -1, sizeof(linker)); for(int u=1; u<=uN; u++){ memset(used, false, sizeof(used)); if(dfs(u)) res++; } return res; } int vis[MAXN]; bool check() //判斷是否是二分圖 { queue<int> q; memset(vis, false, sizeof(vis)); q.push(1); vis[1]=true; while(!q.empty()) { int u=q.front(); q.pop(); for(int i=0; i<G[u].size(); i++) { int v=G[u][i]; if(!vis[v]) { if(vis[u]==1) vis[v]=2; else vis[v]=1; //這裡的染色別弄錯了 //if(vis[u]) vis[v]=2; else vis[v]=1; WA q.push(v); } else if(vis[u]==vis[v]) return false; } } return true; } int main() { int n, m; while(scanf("%d%d",&n,&m)!=EOF){ uN=n; for(int i=0; i<=n; i++) G[i].clear(); while(m--){ int u, v; scanf("%d%d",&u,&v); G[u].push_back(v); G[v].push_back(u); } if(check()) cout<<hungary()/2<<endl; else cout<<"No"<<endl; } return 0; }
View Code