您的位置:首页 > 其它

hdu 2444 The Accomodation of Students

2011-08-26 12:28 399 查看
判断是不是二分图,如果是的话输出最大匹配数。

判断用二分图染色,DFS下就好。

#include <map>
#include <set>
#include <queue>
#include <stack>
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <limits.h>
#include <string.h>
#include <string>
#include <algorithm>
#define MID(x,y) ( ( x + y ) >> 1 )
#define L(x) ( x << 1 )
#define R(x) ( x << 1 | 1 )
#define BUG puts("here!!!")
#define STOP system("pause")

using namespace std;

const int MAX = 210;

int a[MAX][MAX];
int col[MAX];
bool flag;

void DFS(int x,int n,int c)
{
	for(int i=1; i<=n; i++)
		if( a[x][i] )
		{
			if( col[i] == c )
				continue;
			if( col[i] == 0 )
			{
				col[i] = c;
				DFS(i, n, -c);
			}
			else
			{
				flag = false;
				return ;
			}
			if( flag == false ) return ;
		}
}

bool is_2(int n)
{
	flag = true;
	memset(col, 0, sizeof(col));
	col[1] = -1;
	DFS(1, n, 1);
	return flag;
}

int used[MAX],mat[MAX];

int Augment(int s,int n,int x)
{
	int i;
	for(i=s; i<=n; i++)
		if( !used[i] && a[x][i] )
		{
			used[i] = 1;
			if( mat[i] == -1 || Augment(s,n,mat[i]) )
			{
				mat[i] = x;
				return 	1;
			}
		}
	return 0;
}
int Hungary(int s,int n)
{
	int i,sum = 0;
	memset(mat,-1,sizeof(mat));
	for(i=s; i<=n; i++)
	{
		memset(used,0,sizeof(used));
		if( Augment(s,n,i) )
			sum++;
	}
	return sum;
}
int main()
{
	int n, m, u, v;
	
	while( ~scanf("%d%d", &n, &m) )
	{
		memset(a, 0, sizeof(a));

		while( m-- )
		{
			scanf("%d%d", &u, &v);
			a[u][v] = a[v][u] = 1;
		}
		
		if( !is_2(n) )
		{
			printf("No\n");
			continue;
		}
		int ans = Hungary(1,n);
		printf("%d\n", ans/2);
	}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: