POJ 1273
思路:最大流算法,基于FF方法:
1.Dinic:
/*************************************************************************
> File Name: Dith.cpp
> Author: wangzhili
> Mail: wangstdio.h@gmail.com
> Created Time: 2014年03月07日 星期五 10时47分22秒
************************************************************************/
#include<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
#define MAX 205
using namespace std;
int res[MAX][MAX], level[MAX], N, M;
queue<int>q;
bool bfs(int s)
{
memset(level, -1, sizeof(level));
while(!q.empty()) q.pop();
level[s] = 0;
q.push(s);
while(!q.empty())
{
int p = q.front();
q.pop();
for(int i = 1;i <= M;i ++)
{
if(level[i] == -1 && res[p][i] > 0)
{
level[i] = level[p] + 1;
q.push(i);
}
}
}
if(level[M] >= 0)
return true;
return false;
}
int Dinic(int s, int sum)
{
if(s == M)
return sum;
int os = sum;
for(int i = 1;i <= M;i ++)
{
if(level[i] == level[s] + 1 && res[s][i] > 0)
{
int temp = Dinic(i, min(sum, res[s][i]));
res[s][i] -= temp;
res[i][s] += temp;
sum -= temp;
}
}
return os - sum;
}
int main(int argc, char const *argv[])
{
int flow, u, v, w;
// freopen("in.c", "r", stdin);
while(cin >> N >> M)
{
flow = 0;
memset(res, 0, sizeof(res));
while(N--)
{
cin >> u >> v >> w;
res[u][v] += w;
}
while(bfs(1))
flow += Dinic(1, 1 << 30);
cout << flow << endl;
}
return 0;
}2.EK:
/*************************************************************************
> File Name: EK.cpp
> Author: wangzhili
> Mail: wangstdio.h@gmail.com
> Created Time: 2014年03月07日 星期五 11时08分35秒
************************************************************************/
#include<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
#define MAX 205
using namespace std;
int res[MAX][MAX], vis[MAX], pre[MAX], N, M;
queue<int>q;
bool bfs(int s, int t)
{
memset(vis, 0, sizeof(vis));
memset(pre, -1, sizeof(pre));
while(!q.empty()) q.pop();
vis[s] = 1;
q.push(s);
while(!q.empty())
{
int p = q.front();
q.pop();
for(int i = 1;i <= M;i ++)
{
if(!vis[i] && res[p][i] > 0)
{
vis[i] = 1;
pre[i] = p;
if(i == t)
return true;
q.push(i);
}
}
}
return false;
}
int EK(int s, int t)
{
int d, u;
d = 1 << 30;
u = t;
while(pre[u] != -1)
{
d = min(d, res[pre[u]][u]);
u = pre[u];
}
u = t;
while(pre[u] != -1)
{
res[pre[u]][u] -= d;
res[u][pre[u]] += d;
u = pre[u];
}
return d;
}
int main(int argc, char const *argv[])
{
int u, v, w, flow;
// freopen("in.c", "r", stdin);
while(cin >> N >> M)
{
flow = 0;
memset(res, 0, sizeof(res));
while(N--)
{
cin >> u >> v >> w;
res[u][v] += w;
}
while(bfs(1, M))
flow += EK(1, M);
cout << flow << endl;
}
return 0;
}
浙公网安备 33010602011771号