题目链接:https://vjudge.net/problem/POJ-1815
题意:求s点到t点,最少去掉几个点使得他们不连通。如果无解输出NO ANSWER!
解法:
#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 1010;
const int maxm = 100010;
const int inf = 0x3f3f3f3f;
int n, st, en;
int start[maxn][maxn];
bool del[maxn];
vector <int> path;
struct G
{
int v, cap, next;
G() {}
G(int v, int cap, int next) : v(v), cap(cap), next(next) {}
} E[maxm];
int p[maxn], T;
int d[maxn], temp_p[maxn], qw[maxn]; //d顶点到源点的距离标号,temp_p当前狐优化,qw队列
void init()
{
memset(p, -1, sizeof(p));
T = 0;
}
void add(int u, int v, int cap)
{
E[T] = G(v, cap, p[u]);
p[u] = T++;
E[T] = G(u, 0, p[v]);
p[v] = T++;
}
bool bfs(int st, int en, int n)
{
int i, u, v, head, tail;
for(i = 0; i <= n; i++) d[i] = -1;
head = tail = 0;
d[st] = 0;
qw[tail] = st;
while(head <= tail)
{
u = qw[head++];
for(i = p[u]; i + 1; i = E[i].next)
{
v = E[i].v;
if(d[v] == -1 && E[i].cap > 0)
{
d[v] = d[u] + 1;
qw[++tail] = v;
}
}
}
return (d[en] != -1);
}
int dfs(int u, int en, int f)
{
if(u == en || f == 0) return f;
int flow = 0, temp;
for(; temp_p[u] + 1; temp_p[u] = E[temp_p[u]].next)
{
G& e = E[temp_p[u]];
if(d[u] + 1 == d[e.v])
{
temp = dfs(e.v, en, min(f, e.cap));
if(temp > 0)
{
e.cap -= temp;
E[temp_p[u] ^ 1].cap += temp;
flow += temp;
f -= temp;
if(f == 0) break;
}
}
}
return flow;
}
void build(){
init();
for(int i=1; i<=n; i++){
if(!del[i]) add(i,i+n,1);
}
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
if(start[i][j])
add(i+n, j, inf);
}
int dinic(int st, int en, int n)
{
int i, ans = 0;
while(bfs(st, en, n))
{
for(i = 0; i <= n; i++) temp_p[i] = p[i];
ans += dfs(st, en, inf);
}
return ans;
}
int main(){
scanf("%d %d %d", &n,&st,&en);
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
scanf("%d", &start[i][j]);
if(start[st][en]){
return 0*printf("NO ANSWER!\n");
}
st = st+n, en = en;
build();
int ans = dinic(st, en, 2*n+1);
printf("%d\n", ans);
if(!ans) return 0;
for(int i=1; i<=n; i++){
//因为割点可能会有很多组合,而且要求字典序最小,所以只能割一个就标记上,一直到割完为止
if(i==st-n||i==en) continue;
del[i] = 1;
build();
int t = dinic(st, en, 2*n+1);
if(t < ans){
ans--;
path.push_back(i);
if(ans==0) break;
}else
del[i] = false;
}
for(int i=0; i<path.size(); i++){
if(i==path.size()-1) printf("%d\n", path[i]);
else printf("%d ", path[i]);
}
return 0;
}