算法思路:网络流。
比较简单的模板题,bfs实现的EK算法,算法框架来自刘汝佳的《算法竞赛》。maxflow(int s, int t)中的s, t分别代表源点和汇点。
不过要注意:
1.有多个case;
2.会有平行边,输入的时候相加就行了。
测试数据:
3 3
1 2 5
1 2 6
2 3 10
ans=10
//模板开始
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>
#include <map>
#include <set>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <string.h>
#include <queue>
#define SZ(x) (int(x.size()))
using namespace std;
int toInt(string s){
istringstream sin(s);
int t;
sin>>t;
return t;
}
template<class T> string toString(T x){
ostringstream sout;
sout<<x;
return sout.str();
}
typedef long long int64;
int64 toInt64(string s){
istringstream sin(s);
int64 t;
sin>>t;
return t;
}
template<class T> T gcd(T a, T b){
if(a<0)
return gcd(-a, b);
if(b<0)
return gcd(a, -b);
return (b == 0)? a : gcd(b, a % b);
}
//模板结束(通用部分)
#define ifs cin
#define MAXN 250
int flow[MAXN][MAXN];
queue<int> q;
int f;
int a[MAXN];
int n, m;
int cap[MAXN][MAXN];
int p[MAXN];
#define INF 1<<30;
int maxflow(int s, int t)
{
memset(flow, 0, sizeof(flow));
f = 0;
for( ; ; )
{
memset(a, 0, sizeof(a));
a[s] = INF;
q.push(s);
while(!q.empty())
{
int u = q.front();
q.pop();
for(int v = 1; v <= n; v++)
{
if(!a[v] && cap[u][v] > flow[u][v])
{
p[v] = u;
q.push(v);
if(a[u] >= cap[u][v] - flow[u][v])
{
a[v] = cap[u][v] - flow[u][v];
}
else
{
a[v] = a[u];
}
}
}
}
if(a[t] == 0)
{
break;
}
for(int u = t; u != s; u = p[u])
{
flow[p[u]][u] += a[t];
flow[u][p[u]] -= a[t];
}
f += a[t];
}
return f;
}
//【图论03】网络流 1001 Drainage Ditches
int main()
{
//ifstream ifs("shuju.txt", ios::in);
while(ifs>>n>>m)
{
for(int i = 1; i <= m; i++)
{
for(int j = 1; j <= m; j++)
{
cap[i][j] = 0;
}
}
int a, b, c;
for(int i = 0; i < n; i++)
{
ifs>>a>>b>>c;
cap[a][b] += c;
}
int f = maxflow(1, m);
cout<<f<<endl;
}
return 0;
}