HDU - 2444——The Accomodation of Students(判断二分图,二分图最大匹配)
題意:
題意: 有n個人,m對人相互認識; 問能否分成兩個組,組內任意兩個人之間不認識; 若不能,則輸出No; 若能,則相互認識的兩個人一間房,求最多需要幾間房;
給出一些學生的認識情況,比如A和B認識,B和C認識,但是A和C不一定認識。現在問能否將這些學生分成兩個組,并且每組中的學生互相不認識,如果能分,求出最大能匹配的學生對數。
題目
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.
Sample Input
4 4
1 2
1 3
1 4
2 3
6 5
1 2
1 3
1 4
2 5
3 6
Sample Output
No
3
題解:
1首先bfs判斷是否是二分圖,然后求二分最大匹配。
2判斷是否為二分圖:在無向圖G中,無向圖G為二分圖的充分必要條件是:G至少有兩個頂點,且當存在回路時,其所有回路的長度均為偶數。回路就是環路,也就是判斷是否存在奇數環。如果存在奇數回路(回路中節點個數為奇數),則不是二分圖。否則是二分圖。
采用染色法+bfs(染色法是將一個點先染色,然后把和它相鄰的點染成不同的顏色,如果遇到相鄰點的顏色相同的情況就不是二分圖)
3 染色法判斷回路奇偶性:把相鄰兩點染成黑白兩色,如果相鄰兩點出現顏色相同則存在奇數回路。也就是非二分圖。
4匹配的對數:由于是兩個相同的集合進行配對,所以最后將結果除2
AC代碼
#include<stdio.h> #include<string.h> #include<queue> #include<algorithm> using namespace std; const int M=2e2+10; int n,m,dp[M],book[M],e[M],map[M][M]; bool dfs()//先要判斷能否分成兩組,使得每組內的人互不認識,即判斷是否為二分圖 {memset(dp,-1,sizeof(dp));//染色數組,-1為未染,0,1則為兩種不同顏色for(int i=1; i<=n; i++){if(dp[i]!=-1)continue;dp[i]=0;queue<int>q;q.push(i);while(!q.empty()){int head=q.front();q.pop();for(int j=1; j<=n; j++){if(!map[head][j])continue;if(dp[j]!=-1&&dp[head]==dp[j])//把相鄰兩點染成黑白兩色,如果相鄰兩點出現顏色相同則存在奇數回路。也就是非二分圖。return false;else if(dp[j]==-1){dp[j]=!dp[head];q.push(j);}}}}return true; } bool math(int x)//匈牙利算法 {for(int i=1; i<=n; i++)if(!book[i]&&map[x][i]){book[i]=1;if(!e[i]||math(e[i])){e[i]=x;return true;}}return false; } int main() {while(~scanf("%d%d",&n,&m)){memset(map,0,sizeof(map));for(int i=1; i<=m; i++){int a,b;scanf("%d%d",&a,&b);map[a][b]=map[b][a]=1;}if(dfs()==false){printf("No\n");continue;}int ans=0;memset(e,0,sizeof(e));for(int i=1; i<=n; i++){memset(book,0,sizeof(book));if(math(i))ans++;}printf("%d\n",ans/2);//求對數,除2}return 0; }總結
以上是生活随笔為你收集整理的HDU - 2444——The Accomodation of Students(判断二分图,二分图最大匹配)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 人心果的功效与作用、禁忌和食用方法
- 下一篇: Round Numbers POJ -