【BZOJ2718】[Violet 4]毕业旅行【最长反链】【传递闭包】

【题目链接】

同【BZOJ1143题解】

注意数据范围大了点...

/* Pigonometry */
#include <cstdio>
#include <algorithm>

using namespace std;

const int maxn = 505, maxm = 20005;

int n, m, head[maxn], cnt, from[maxn], vis[maxn], clo;
bool mp[maxn][maxn];

struct _edge {
	int v, next;
} g[maxm];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline void add(int u, int v) {
	g[cnt] = (_edge){v, head[u]};
	head[u] = cnt++;
}

inline bool hungary(int x) {
	for(int i = head[x]; ~i; i = g[i].next) if(vis[g[i].v] ^ clo) {
		vis[g[i].v] = clo;
		if(!from[g[i].v] || hungary(from[g[i].v])) {
			from[g[i].v] = x;
			return 1;
		}
	}
	return 0;
}

int main() {
	n = iread(); m = iread();
	for(int i = 1; i <= n; i++) head[i] = -1; cnt = 0;

	for(int i = 1; i <= m; i++) {
		int u = iread(), v = iread();
		mp[u][v] = 1;
	}

	for(int k = 1; k <= n; k++) for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++)
		mp[i][j] |= mp[i][k] & mp[k][j];

	for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) if(i ^ j && mp[i][j])
		add(i, j);

	int ans = n;
	for(int i = 1; i <= n; i++) clo++, ans -= hungary(i);

	printf("%d\n", ans);
	return 0;
}


你可能感兴趣的:(传递闭包,最长反链)