The Accomodation of Students

来源:互联网 发布:淘宝王成勇培训靠谱吗 编辑:程序博客网 时间:2024/05/21 17:09
典型的二分图最大匹配题
 我们要先判断这个图是不是二分图,可以用染色法来实现
#include <iostream>#include <stdlib.h>#include <stdio.h>#include <string.h>using namespace std;#define MAXN 222bool gra[MAXN][MAXN], vis[MAXN];int  match[MAXN], col[MAXN];int ans, n;bool  check(int cur, int color){    col[cur] = color;    for( int i = 1; i <= n; i++)    {        if(gra[cur][i])        {            if(col[i] != -1)              {                   if(col[i] == color)                    return false;              }            else if(!check(i, !color))                return 0;        }    }    return 1;}bool dfs( int x){    for( int i = 1; i <= n; i++)    {        if( i != x && gra[x][i] && !vis[i])        {            vis[i] = 1;            if(!match[i] || dfs(match[i]))            {                match[i] = x;                return 1;            }        }    }    return 0;}void solve( ){    ans = 0;    for(int i = 1; i <= n; i++)    {        memset(vis, 0, sizeof(vis));        if(dfs(i)) ans++;    }    printf("%d\n",ans/2);}int main(){    int u, v, m;    while(scanf("%d %d",&n, &m) != EOF)    {        memset(gra, 0, sizeof(gra));        memset(match, 0, sizeof(match));        memset(col, -1, sizeof(col));        for(int i = 0; i < m; i++)        {            scanf("%d %d",&u, &v);            gra[u][v] = gra[v][u] = 1;        }        if(!check(1,1))           printf("No\n");        else            solve();    }    return 0;}
0 0
原创粉丝点击