题意:
就是求最小割点
解析:
正向一遍spfa 反向一遍spfa 然后遍历每一条边,对于当前边 如果dis1[u] + dis2[v] + 1 <= k 那么就把这条边加入到网络流图中,
每个点拆点 边权为1
跑最大流即可
代码还是改的那一题。。。
#include <iostream> #include <cstring> #include <cstdio> #include <queue> #include <cmath> #include <vector> #define mem(a,b) memset(a,b,sizeof(a)) using namespace std; const int maxn = 1e3 + 10, INF = 0xfffffff, maxm = 100010; typedef long long LL; int n,m, cnt, s, t, k; int head[maxn], d[maxn], vis[maxn], dis1[maxn], dis2[maxn], head1[maxn], cur[maxn]; int from[maxm], to[maxm]; int bz[55][55], way[55][55]; struct edge { int u, v, c, next; }Edge[maxm << 1]; void add_(int u, int v, int c) { Edge[cnt].u = u; Edge[cnt].v = v; Edge[cnt].c = c; Edge[cnt].next = head1[u]; head1[u] = cnt++; } void add_edge(int u, int v, int c) { add_(u, v, c); add_(v, u, 0); } bool bfs() { mem(d, 0); queue<int> Q; Q.push(s); d[s] = 1; while(!Q.empty()) { int u = Q.front(); Q.pop(); for(int i = head1[u]; i != -1; i = Edge[i].next) { edge e = Edge[i]; if(!d[e.v] && e.c > 0) { d[e.v] = d[u] + 1; Q.push(e.v); if(e.v == t) return 1; } } } return d[t] != 0; } int dfs(int u, int cap) { int ret = 0; if(u == t || cap == 0) return cap; for(int &i = cur[u]; i != -1; i = Edge[i].next) { edge e = Edge[i]; if(d[e.v] == d[u] + 1 && e.c > 0) { int V = dfs(e.v, min(e.c, cap)); Edge[i].c -= V; Edge[i ^ 1].c += V; ret += V; cap -= V; if(cap == 0) break; } } if(cap > 0) d[u] = -1; return ret; } int Dinic() { int ans = 0; while(bfs()) { memcpy(cur, head1, sizeof(head1)); ans += dfs(s, INF); } return ans; } struct node { int u, v, w, next; }Node[maxn * 10]; void add(int u,int v,int w,int i) { Node[i].u = u; Node[i].v = v; Node[i].w = w; Node[i].next = head[u]; head[u] = i; } void spfa(int s) { for(int i = 0; i < maxn; i++) d[i] = INF; queue<int> Q; d[s] = 0; mem(vis,0); Q.push(s); vis[s] = 1; while(!Q.empty()) { int u = Q.front();Q.pop(); vis[u] = 0; for(int i=head[u]; i!=-1; i=Node[i].next) { node e = Node[i]; if(d[e.v] > d[u] + e.w) { d[e.v] = d[u] + e.w; if(!vis[e.v]) { Q.push(e.v); vis[e.v] = 1; } } } } } int main() { int T,A,B; while(~scanf("%d%d%d", &n, &m, &k)) { if(n==0&&m==0&&k==0) break; mem(way, 0); mem(bz, 0); mem(Node,0); mem(head,-1); mem(head1, -1); cnt = 0; for(int i=0; i<m; i++) { scanf("%d%d",&from[i],&to[i]); if(!bz[from[i]][to[i]]) { add(from[i],to[i],1,i), bz[from[i]][to[i]] = 1; way[from[i]][to[i]] = 1; } } s = 1, t = n; spfa(s); mem(Node,0); for(int i=1; i<=n; i++) dis1[i] = d[i]; mem(head,-1); for(int i=0; i<m; i++) add(to[i],from[i],1,i); spfa(t); for(int i=1; i<=n; i++) dis2[i] = d[i]; mem(bz, 0); s = 1 + n, t = n; for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { if(way[i][j] && dis1[i] + dis2[j] + 1 <= k) add_edge(i, j, INF); } add_edge(i, i + n, 1); } printf("%d ",Dinic()); } return 0; }