试题 算法训练 网络流裸题
资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
一个有向图,求1到N的最大流
输入格式
第一行N M,表示点数与边数
接下来M行每行s t c表示一条从s到t的容量为c的边
输出格式
一个数最大流量
样例输入
6 10
1 2 4
1 3 8
2 3 4
2 4 4
2 5 1
3 4 2
3 5 2
4 6 7
5 4 6
5 6 3
样例输出
8
数据约定:
n<=1000 m<=10000
#include <bits/stdc++.h>
using namespace std;
int N,M;
int s,t;
int res;
map<int,map<int,int> > mp;
vector<int> a;
vector<int> pre;
void Solution(){
queue<int> que;
while(1){//从源点开始找
a.assign(N+1,0); //初始化 a
a[s]=INT_MAX; //源点相当于有无限的流量
que.push(s); //每次都是从源点开始找
while(!que.empty()){ //bfs找增广路
int v=que.front();
que.pop();
for(map<int,int>::iterator i=mp[v].begin();i!=mp[v].end();++i){
if(!a[i->first]&&i->second>0){
pre[i->first]=v;
a[i->first]=min(a[v],i->second);
que.push(i->first);
}
}
}
if(a[t]==0)return;//没有剩余的流量了
res+=a[t];
for(int i=N;i!=1;i=pre[i]){//更新走过的路的流量
mp[pre[i]][i]-=a[t];
mp[i][pre[i]]+=a[t];
}
}
}
int main(){
cin>>N>>M;
for(int i=0;i<M;++i){
int k,j,l;
cin>>k>>j>>l;
mp[k][j]+=l;//是+= 不是= 一条边可能会重复出现
}
s=1;//源点
t=N;//汇点
pre.assign(N+1,0);
Solution();
cout<<res<<endl;
return 0;
}