传送门:http://poj.org/problem?id=3469
题意:
有n个模块,可以在核A或核B上运行,花费分别为Ai、Bi。有m对模块,如果它们不在同一个核上运行,需要额外花费wi。问最小花费是多少。
思路:
题意即将n个模块分成两个集合求最小费用,那么建图后转换成最小割问题就可以解决了。
建立超级源点S和超级汇点T,分别都连向代表每个模块的结点,边容量分别为Ai、Bi,之后m对模块分别连边,容量为wi。
利用最大流最小割定理,跑一遍最大流就可以了。
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<utility>
#include<algorithm>
#include<utility>
#include<queue>
#include<vector>
#include<set>
#include<stack>
#include<cmath>
#include<map>
#include<ctime>
#include<functional>
#define P pair<int,int>
#define ll long long
#define ull unsigned long long
#define lson id*2,l,mid
#define rson id*2+1,mid+1,r
#define ls id*2
#define rs id*2+1
#define Mod(a,b) a<b?a:a%b+b
using namespace std;
const int maxn = 100010;
const ll M = 1e9 + 7;
const ll INF = 1e9;
const int N = 20010;
const double e = 10e-6;
const int dx[4] = { 0,0,1,-1 }, dy[4] = { 1,-1,0,0 };
struct edge { int to; ll cap; int rev; };
vector<edge>G[N];
int level[N], iter[N];
void addEdge(int from, int to, ll cap)
{
G[from].push_back(edge{ to,cap,(int)G[to].size() });
G[to].push_back(edge{ from,0,(int)G[from].size() - 1 });
}
void init()
{
for (int i = 0; i < N; i++)
G[i].clear();
}
void bfs(int s)
{
memset(level, -1, sizeof(level));
queue<int> que;
level[s] = 0; que.push(s);
while (!que.empty()) {
int v = que.front(); que.pop();
for (int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (e.cap > 0 && level[e.to] < 0) {
level[e.to] = level[v] + 1;
que.push(e.to);
}
}
}
}
ll dfs(int v, int t, ll f)
{
if (v == t) return f;
for (int &i = iter[v]; i < G[v].size(); i++) {
edge &e = G[v][i];
if (e.cap > 0 && level[v] < level[e.to]) {
ll d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
ll maxFlow(int s, int t)
{
ll flow = 0;
while (1) {
bfs(s);
if (level[t] < 0) return flow;
memset(iter, 0, sizeof(iter));
ll f;
while ((f = dfs(s, t, INF)) > 0)
flow += f;
}
}
int n, m, a, b, x;
int main() {
int S = 0, T = 1;
while (~scanf("%d%d", &n, &m)) {
init();
for (int i = 0; i < n; i++) {
scanf("%d%d", &a, &b);
addEdge(S, i + 2, a);
addEdge(i + 2, T, b);
}
for (int i = 0; i < m; i++) {
scanf("%d%d%d", &a, &b, &x);
addEdge(a + 1, b + 1, x);
addEdge(b + 1, a + 1, x);
}
printf("%lld\n", maxFlow(S, T));
}
return 0;
}