bzoj2718
二分图匹配
首先有个定理:最长反链=最小链覆盖
最小链覆盖可以重复经过点
所以我们不能直接建图
那么我们用floyd判断是否相连
然后建图就行了
#include<bits/stdc++.h> using namespace std; const int N = 410, inf = 1e9; int rd() { int x = 0, f = 1; char c = getchar(); while(c < '0' || c > '9') { if(c == '-') f = -1; c = getchar(); } while(c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); } return x * f; } int n, m, k, D, source, sink, cnt = 1, tot; int a[N], d[N], head[N], iter[N], Map[N][N]; struct edge { int nxt, to, f; } e[N * N]; bool bfs() { queue<int> q; memset(d, -1, sizeof(d)); d[source] = 0; q.push(source); while(!q.empty()) { int u = q.front(); q.pop(); for(int i = head[u]; i; i = e[i].nxt) if(d[e[i].to] == -1 && e[i].f) { d[e[i].to] = d[u] + 1; q.push(e[i].to); } } return d[sink] != -1; } int dfs(int u, int delta) { if(u == sink) return delta; int ret = 0; for(int &i = iter[u]; i && delta; i = e[i].nxt) if(d[e[i].to] == d[u] + 1 && e[i].f) { int x = dfs(e[i].to, min(delta, e[i].f)); ret += x; delta -= x; e[i].f -= x; e[i ^ 1].f += x; } return ret; } int dinic() { int ret = 0; while(bfs()) { for(int i = source; i <= sink; ++i) iter[i] = head[i]; ret += dfs(source, inf); } return ret; } void link(int u, int v, int f) { e[++cnt].nxt = head[u]; head[u] = cnt; e[cnt].to = v; e[cnt].f = f; } void insert(int u, int v, int f) { link(u, v, f); link(v, u, 0); } int main() { scanf("%d%d", &n, &m); sink = 2 * n + 1; for(int i = 1; i <= m; ++i) { int u, v; scanf("%d%d", &u, &v); Map[u][v] = 1; } for(int k = 1; k <= n; ++k) { insert(source, k, 1); insert(k + n, sink, 1); for(int i = 1; i <= n; ++i) for(int j = 1; j <= n; ++j) Map[i][j] |= (Map[i][k] & Map[k][j]); } for(int i = 1; i <= n; ++i) for(int j = 1; j <= n; ++j) if(Map[i][j]) insert(i, j + n, 1); printf("%d\n", n - dinic()); return 0; }