题意:给出一个流网络,给出源点和汇点。现在想把某些边反向,让源点到汇点的总流量最大。求出需要反向的边。
思路:对于一个有向流网络,其可能的最大的流量是其对应的无向流网络的最大流,这也是有向流网络的最大流量。然后,对于原来的流网络的每条边,如果流量为正,不需反向。流量为负,需要反向。
代码如下:
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAX = 200000;
struct edge{
int from,to,num;
int cap,flow;
edge(int u= 0,int v=0,int c=0,int f=0):from(u),to(v),cap(c),flow(f){}
};
struct ISAP{
int head[MAX];
int next[MAX];
int tot;
edge edges[2 * MAX];
int que[MAX],front,tail;
int d[MAX];
bool vis[MAX];
int num[MAX];
int pre[MAX];
int cur[MAX];
int s,t,n;
edge cut[2 * MAX];
int cut_cnt;
void init(int n){
this->n = n;
memset(head,-1,sizeof(head));
tot = cut_cnt = 0;//
}
void addedge(int from,int to, int cap){
edges[tot] = edge{from,to,cap,0};//注意无向边和有向边
next[tot] = head[from], head[from] = tot++;
edges[tot] = edge{to,from,cap,0};
next[tot] = head[to],head[to] = tot++;
}
void bfs(){
memset(vis,0,sizeof(vis));
front = tail = 0;
d[t] = 0;
vis[t] = true;
que[tail++] = t;
while(front < tail){
int u = que[front++];
for(int v = head[u]; v != -1; v = next[v]){
edge & e = edges[v^1];
if(e.cap > e.flow && !vis[e.from]){
d[e.from] = d[u] + 1;
vis[e.from] = true;
que[tail++] = e.from;
}
}
}
}
int Augment(){
int x = t,a = INF;
while(x != s){
edge& e = edges[pre[x]];
a = min(a,e.cap - e.flow);
x = e.from;
}
x = t;
while(x != s){
edges[pre[x]].flow += a;
edges[pre[x]^1].flow -= a;
x = edges[pre[x]].from;
}
return a;
}
int maxflow(int s, int t){
this->s = s, this->t = t;
memset(num,0,sizeof(num));
int flow = 0;
bfs();
for(int i = 1; i <= n; ++i){
num[d[i]]++,cur[i] = head[i];
}
int x = s;
while(d[s] < n){
if(x == t){
flow += Augment();
x = s;
}
bool ok = false;
for(int &v = cur[x]; v != -1; v = next[v]){
edge& e = edges[v];
if(e.cap > e.flow && d[x] == d[e.to] + 1){
ok = true;
pre[x = e.to] = v;
break;
}
}
if(!ok){
int m = n - 1;
for(int v = head[x]; v != -1; v = next[v]){
edge & e = edges[v];
if(e.cap > e.flow) m = min(m,d[e.to]);
}
if(--num[d[x]] == 0) break;
num[d[x]=m+1]++;
cur[x] = head[x];
if(x != s) x = edges[pre[x]].from;
}
}
return flow;
}
void mincut(){
bfs();
for(int i = 0 ;i < tot; ++i){
edge & e = edges[i];
if(!vis[e.from] && vis[e.to] && e.cap > 0)
cut[cut_cnt++] = e;
}
}
void print(){
printf("Graph:\n");
for(int i = 0 ; i < tot; ++i){
edge & e = edges[i];
printf("%d->%d c:%d f:%d\n",e.from,e.to,e.cap,e.flow);
}
}
void solve(int s, int t){
printf("%d\n",maxflow(s,t));
vector<int> ans;
for(int i = 0; i < tot; i += 2){
edge & e = edges[i];
if(e.flow < 0 )
ans.push_back(i / 2 + 1);
}
printf("%d\n",ans.size());
for(int i = 0, sz = ans.size(); i < sz; ++ i)
printf("%d\n",ans[i]);
}
}solve;
int main(void)
{
//freopen("input.txt","r",stdin);
int N,M;
int u,v;
int s,t;
scanf("%d %d", &N,&M);
solve.init(N);
for(int i = 0; i < M; ++i){
scanf("%d %d", &u,&v);
solve.addedge(u,v,1);
}
scanf("%d %d", &s,&t);
solve.solve(s,t);
return 0;
}