https://www.patest.cn/contests/pat-t-practise/1003
参考了:
http://blog.sina.com.cn/s/blog_6cf509db0100uy5n.html
http://blog.youkuaiyun.com/zorelemn/article/details/50410853
http://blog.youkuaiyun.com/jtjy568805874/article/details/50759478
#include <cstdio>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <climits>
#include <algorithm>
using namespace std;
/*
* Find a augmented path
*/
bool bfs(vector< vector<int> >& g,vector<int> &pre, int np, int src, int dist) {
fill(pre.begin(),pre.end(), -1);
queue<int> q;
q.push(src);
while (!q.empty()) {
int t = q.front();
q.pop();
for (int i = 1; i < np; i++)
{
if (g[t][i] != 0 && pre[i] == -1) {
pre[i] = t;
if (i == dist) return true;
q.push(i);
}
}
}
return false;
}
int maxFlow(vector<vector<int> > g, int np, int src, int dist) {
int flow = 0, d;
vector<int> pre(1005,-1);
while (bfs(g, pre, np, src, dist)) {//find an augmented path
d = INT_MAX;
//get the max_flow of the augmented path
for (int i = dist; i != src; i = pre[i])
{
d = min(d, g[pre[i]][i]);
}
for (int i = dist; i != src; i = pre[i])
{
g[pre[i]][i] -= d;
g[i][pre[i]] += d;
}
flow += d;
}
return flow;
}
int main()
{
int n, c, np = 1;
char a[4], b[4];
map<string,int> idsM;
vector< vector<int> > G(1005, vector<int>(1005, 0));
scanf("%s %s %d", a, b, &n);
if (!idsM[a]) idsM[a] = np++;
if (!idsM[b]) idsM[b] = np++;
for (int i = 0; i < n; i++)
{
scanf("%s %s %d", a, b, &c);
if (!idsM[a]) idsM[a] = np++;
if (!idsM[b]) idsM[b] = np++;
G[idsM[a]][idsM[b]] = c;
}
int maxF = maxFlow(G,np,1,2);
printf("%d\n", maxF);
return 0;
}