Drainage Ditches-max_flow
update@2011-08-23
int Edmonds_Karp(int source, int sink, int vertex_num)
{
int maxFlow = 0;
while(true) {
int head, tail, pre_of[UPPER], my_stack[UPPER];
head = tail = 0;//初始化栈
my_stack[tail++] = source;//放入源点
memset(pre_of, -1, sizeof(pre_of));//pre_of[v],v 代表边u v
while(head < tail){
int u = my_stack[head++];//取出u点
for(int v = 1; v <= vertex_num; v ++){
if(residual[u][v] > 0 && pre_of[v] == -1) {
my_stack[tail++] = v;/*入栈*/pre_of[v] = u;/*保存这条边*/
if(u == sink) break;
}
}
if(pre_of[sink] != -1) break;//找到增广路径
}
if(pre_of[sink] == -1) break;//没有增广路径
int min_flow = INF;
for(int v = sink; v != source; v = pre_of[v]) {
min_flow = mymin(min_flow, residual[pre_of[v]][v]);
//对pre保存的路径进行回溯找到最小的流
}
maxFlow += min_flow;
for(int v = sink; v != source; v = pre_of[v]) {//更新流网络
residual[pre_of[v]][v] -= min_flow;
residual[v][pre_of[v]] += min_flow;
}
}
return maxFlow;
}
题目链接:
Drainage Ditches基础的最大流问题,先google下Ford-Fulkerson熟悉最大流及求解思想,再来做这个题。最开始自己写DFS 无数次WA,最后改了两个地方是TLE :( ,有些地方还是不清楚,无语中....无奈套模板AC..
//部分代码
//纯粹的Ford Fulkerson思想
//纯DFS,回溯时更新流,比模板简单、短很多
//效率略低,10ms
int matrix[200+1][200+1],int pre_of[200+1];
int DFS(int i,int v,int min_flow){
int k;
if(i == v){
pre_of[i] = -1;
return min_flow;
}
for(k = 1;k <= v;k++){
if(pre_of[k] == -1 && matrix[i][k] > 0){
pre_of[k] = i;
int t = DFS(k,v,mymin(min_flow,matrix[i][k]));
if(t != 0){//有一条增广路径
matrix[k][i] += t;matrix[i][k] -= t;
pre_of[k] = -1; return t;
}
}
}
pre_of[i] = -1;
return 0;
}
//main函数中的主要部分
int e,v,i;
while(scanf("%d%d",&e,&v) != EOF){
memset(matrix,0,sizeof(matrix));//0表示没有
memset(pre_of,-1,sizeof(pre_of));
for(i = 0;i < e;i++){
int si,ti,ci;scanf("%d%d%d",&si,&ti,&ci);
matrix[si][ti] += ci;
}
int t,ans = 0;
while((t = DFS(1,v,INF))){memset(pre_of,-1,sizeof(pre_of));ans += t;}
printf("%d\n",ans);
}
终于AC了 好开心啊,郁闷我一晚上啊:),简单的Ford Fulkerson思想,深搜求增广路径不多说了,看代码。