[luoguP1640] [SCOI2010]连续攻击游戏(二分图最大匹配)

传送门

 

我们将每一个属性和物品连边,然后枚举从小到大属性跑匈牙利,直到找不到连边

#include <cstdio>
#include <cstring>
#include <iostream>
#define N 1000001
#define M 2000001

using namespace std;

int n, cnt;
int head[N], to[M], nex[M], belong[N];
bool vis[N];

inline int read()
{
	int x = 0, f = 1;
	char ch = getchar();
	for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1;
	for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0';
	return x * f;
}

inline void add(int x, int y)
{
	to[cnt] = y;
	nex[cnt] = head[x];
	head[x] = cnt++;
}

inline bool dfs(int u)
{
	int i, v;
	for(i = head[u]; ~i; i = nex[i])
	{
		v = to[i];
		if(!vis[v])
		{
			vis[v] = 1;
			if(!belong[v] || dfs(belong[v]))
			{
				belong[v] = u;
				return 1;
			}
		}
	}
	return 0;
}

inline int solve()
{
	int i, ans = 0;
	for(i = 1; i <= 10000; i++)
	{
		memset(vis, 0, sizeof(vis));
		if(dfs(i)) ans++;
		else return ans;
	}
	return ans;
}

int main()
{
	int i, x, y;
	n = read();
	memset(head, -1, sizeof(head));
	for(i = 1; i <= n; i++)
	{
		x = read();
		y = read();
		add(x, i);
		add(y, i);
	}
	printf("%d\n", solve());
	return 0;
}

  

posted @ 2018-01-10 10:39  zht467  阅读(128)  评论(0编辑  收藏  举报