Language:Default
Dual Core CPU
Description As more and more computers are equipped with dual core CPU, SetagLilb, the Chief Technology Officer of TinySoft Corporation, decided to update their famous product - SWODNIW. The routine consists of N modules, and each of them should run in a certain core. The costs for all the routines to execute on two cores has been estimated. Let’s define them as Ai and Bi. Meanwhile, M pairs of modules need to do some data-exchange. If they are running on the same core, then the cost of this action can be ignored. Otherwise, some extra cost are needed. You should arrange wisely to minimize the total cost. Input There are two integers in the first line of input data, N and M (1 ≤ N ≤ 20000, 1 ≤ M ≤ 200000) . Output Output only one integer, the minimum total cost. Sample Input 3 1 1 10 2 10 10 3 2 3 1000 Sample Output 13 Source
POJ Monthly–2007.11.25, Zhou Dong
|
以模块作为顶点
源点S连接到每个模块i,流量为Ai
每个模块i连接到汇点T,流量为Bi
此时 若需要数据交换的(i,j)模块在不同核运行,则需要额外w的花销
在i和j之间 分别连一条(i->j)和(j->i) 流量都为w的边
此时最大流=最小割就是最小花销
#include<stdio.h>
//#include<bits/stdc++.h>
#include<deque>
#include<string>
#include<string.h>
#define ll long long
#define pii pair<int,int>
#define MEM(a,x) memset(a,x,sizeof(a))
#define lowbit(x) ((x)&-(x))
using namespace std;
const int inf=1e9+7;
const int N = 20000 + 5;//点数
const int N2 = 200000 + 5;
const int M = 2*(2*N+2*N2);//边数*2(包括反向边)
int level[N];//标号 level[i]:s到i的最短距离
struct Edge{
int to,c,next;
}edge[M];
int head[N];
inline void add_edge(int k,int u,int v,int c){
edge[k].to = v;
edge[k].c = c;
edge[k].next = head[u];
head[u] = k;
}
int nume=0;
inline void add_edge(int u,int v,int c){
add_edge(nume++,u,v,c);
add_edge(nume++,v,u,0);
}
bool bfs(int s,int t){//标号 计算level
deque<int>que;
MEM(level,-1);
que.push_back(s);
level[s] = 0;
while(!que.empty()){
int u = que.front();
if(u == t){
return true;
}
que.pop_front();
for(int i = head[u];i!=-1;i = edge[i].next){
if(edge[i].c > 0 && level[edge[i].to] == -1){
level[edge[i].to] = level[u] + 1;
que.push_back(edge[i].to);
}
}
}
return false;
}
int dfs(int u,int t,int maxf){//u:所在的点 t:汇点 maxf:能流到u的流量
if(u == t){
return maxf;
}
int sum = 0;
for(int i = head[u];i!=-1;i = edge[i].next){
Edge&e = edge[i];
if(e.c>0 && level[e.to]==level[u]+1){
int f = dfs(e.to,t,min(maxf - sum,e.c));
sum += f;
edge[i].c -= f;
edge[i^1].c += f;
if(sum == maxf){//流量用完了
break;
}
}
}
if(!sum){//剪枝
level[u]=-1;
}
return sum;
}
int dinic(int s,int t){//s:源点 t:汇点 n:点数
int ans = 0;
while(bfs(s,t)){
ans += dfs(s,t,2*inf);
}
return ans;
}
int main()
{
//freopen("/home/lu/code/r.txt","r",stdin);
int n,m;
while(~scanf("%d%d",&n,&m)){
MEM(head,-1);
nume=0;
const int S = n+1,T=S+1;
for(int i=0;i<n;++i){
int a,b;
scanf("%d%d",&a,&b);
add_edge(S,i+1,a);
add_edge(i+1,T,b);
}
for(int i=0;i<m;++i){
int a,b,w;
scanf("%d%d%d",&a,&b,&w);
add_edge(a,b,w);
add_edge(b,a,w);
}
printf("%d\n",dinic(S,T));
}
return 0;
}