【
题意】给定一个N个节点M条边的网络流,求有多少条边,使得当增其中加任何一个边的容量后,整个网络的流将增加. 挺好的一道题,考察对网络流和增广路的理解。 【
思路】 首先关键边一定是满流边。那么对于一个满流边<x,y>来说,如果残余网络中从起点到x和从y到终点都有路径可达的话,那么这条边的容量增加时,在残量网络上将会产生一条增广路,最大流的值一定会发生改变。 则算法如下: 求最大流,得到残余网络 枚举每条满流边,DFS判断是否分别从源点和到汇点可达,如果可达则加1。
#include
#include
#include
#include
#include
#include
#define MID(x,y) ((x+y)/2)
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int MAXV = 505;
const int MAXE = 20005;
const int oo = 0x3fffffff;
struct node{
int u, v, flow;
int opp;
int next;
};
struct Dinic{
node arc[MAXE];
int vn, en, head[MAXV]; //vn点个数(包括源点汇点),en边个数
int cur[MAXV]; //当前弧
int q[MAXV]; //bfs建层次图时的队列
int path[MAXE], top; //存dfs当前最短路径的栈
int dep[MAXV]; //各节点层次
void init(int n){
vn = n;
en = 0;
mem(head, -1);
}
void insert_flow(int u, int v, int flow){
arc[en].u = u;
arc[en].v = v;
arc[en].flow = flow;
arc[en].opp = en + 1;
arc[en].next = head[u];
head[u] = en ++;
arc[en].u = v;
arc[en].v = u;
arc[en].flow = 0; //反向弧
arc[en].opp = en - 1;
arc[en].next = head[v];
head[v] = en ++;
}
bool bfs(int s, int t){
mem(dep, -1);
int lq = 0, rq = 1;
dep[s] = 0;
q[lq] = s;
while(lq < rq){
int u = q[lq ++];
if (u == t){
return true;
}
for (int i = head[u]; i != -1; i = arc[i].next){
int v = arc[i].v;
if (dep[v] == -1 && arc[i].flow > 0){
dep[v] = dep[u] + 1;
q[rq ++] = v;
}
}
}
return false;
}
int solve(int s, int t){
int maxflow = 0;
while(bfs(s, t)){
int i, j;
for (i = 1; i <= vn; i ++) cur[i] = head[i];
for (i = s, top = 0;;){
if (i == t){
int mink;
int minflow = 0x3fffffff;
for (int k = 0; k < top; k ++)
if (minflow > arc[path[k]].flow){
minflow = arc[path[k]].flow;
mink = k;
}
for (int k = 0; k < top; k ++)
arc[path[k]].flow -= minflow, arc[arc[path[k]].opp].flow += minflow;
maxflow += minflow;
top = mink; //arc[mink]这条边流量变为0, 则直接回溯到该边的起点即可(这条边将不再包含在增广路内).
i = arc[path[top]].u;
}
for (j = cur[i]; j != -1; cur[i] = j = arc[j].next){
int v = arc[j].v;
if (arc[j].flow && dep[v] == dep[i] + 1)
break;
}
if (j != -1){
path[top ++] = j;
i = arc[j].v;
}
else{
if (top == 0) break;
dep[i] = -1;
i = arc[path[-- top]].u;
}
}
}
return maxflow;
}
}dinic;
bool vis[MAXV];
bool reach(int u, int p){
vis[u] = 1;
if (u == p)
return true;
for (int i = dinic.head[u]; i != -1; i = dinic.arc[i].next){
int v = dinic.arc[i].v;
if (vis[v] || dinic.arc[i].flow <= 0) continue;
if (reach(v, p))
return true;
}
return false;
}
int work(int n){
int res = 0;
for (int i = 0; i < dinic.en; i += 2){
if (dinic.arc[i].flow == 0){
mem(vis, 0);
int u = dinic.arc[i].u;
int v = dinic.arc[i].v;
if (reach(1, u) && reach(v, n)){
res ++;
}
}
}
return res;
}
int main(){
//freopen("test.in", "r", stdin);
//freopen("test.out", "w", stdout);
int n, m;
scanf("%d %d", &n, &m);
dinic.init(n);
for (int i = 0; i < m; i ++){
int u,v,w;
scanf("%d %d %d", &u, &v, &w);
dinic.insert_flow(u+1, v+1, w);
}
dinic.solve(1, n);
printf("%d\n", work(n));
return 0;
}