题意:CPU有两个核心A,B处理任务。现在有N个任务,需要将这些任务分配到A,B两个核心上执行。执行该任务有费用,费用分为两种:1.单个任务在A,B核执行的费用。2.两个任务如果被分配在不同的核心上执行,会有信息交互的费用。现在让最小化执行完所有任务的费用。
思路:本题是将任务分成两个集合,很容易想到最小割也有这样的性质。现在,我们要想如何建图,是最小割满足题中要求。
总的费用为4项:1.任务在A核心执行的费用,即属于集合S,这个时候要从任务对应的点向汇点t连容量为花费的边。
2.任务在B核心执行的费用,即属于集合T,这个时候要从任务对应的点想源点s连容量为花费的边。
3.任务ai在A核心执行,bi在B核心执行产生的交互费用。这个时候要从ai向bi连容量为花费的边。
4.任务ai在B核心执行,bi在A核心执行产生的交互费用。这个时候要从bi向ai连容量为花费的边。
这样,我们求出最小割就是最小的花费。
代码如下:
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
struct edge{
int from,to;
int cap,flow;
edge(int u =0,int v =0,int c=0,int f=0):from(u),to(v),cap(c),flow(f){}
};
struct ISAP{
static const int INF = 0x3f3f3f3f;
static const int MAX = 500000* 2;//2倍的边的大小
int head[MAX];//每个节点对应链表的开始位置
int next[MAX];//链表的下一个节点在edges数组的位置
int tot;//edges数组的大小
edge edges[MAX];//储存边的数组
int que[MAX],front,tail;//队列,保存节点
int d[MAX];//距离标号
bool vis[MAX];//访问标记
int num[MAX];//gap优化
int pre[MAX];//增广路中,节点X的前面一个弧的标号
int cur[MAX];//对于每个节点的,处理的当前弧。
int s,t,n;//s源点标号,t汇点标号,n节点总数
void init(int n){
this->n = n;//注意此处的下标问题
memset(head,-1,sizeof(int)*(n+1));
tot = 0;//
}
void addedge(int from,int to, int cap){
edges[tot] = edge(from,to,cap,0);
next[tot] = head[from], head[from] = tot++;
edges[tot] = edge(to,from,0,0);
next[tot] = head[to],head[to] = tot++;
}
void bfs(){
memset(vis,0,sizeof(vis));
front = tail = 0;
d[t] = 0;
vis[t] = true;
que[tail++] = t;
while(front < tail){
int u = que[front++];
for(int v = head[u]; v != -1; v = next[v]){
edge & e = edges[v^1];
if(e.cap > e.flow && !vis[e.from]){//对处于残余网络中的弧且没访问过的节点处理
d[e.from] = d[u] + 1;
vis[e.from] = true;
que[tail++] = e.from;
}
}
}
}
int augment(){
int x = t,a = INF;
while(x != s){
edge& e = edges[pre[x]];
a = min(a,e.cap - e.flow);
x = e.from;
}
x = t;
while(x != s){
edges[pre[x]].flow += a;
edges[pre[x]^1].flow -= a;
x = edges[pre[x]].from;
}
return a;
}
int maxflow(int s, int t){
this->s = s, this->t = t;
memset(num,0,sizeof(num));
int flow = 0;
bfs();
for(int i = 0; i <= n; ++i){//注意此处的下标问题
num[d[i]]++;
cur[i] = head[i];
}
int x = s;
while(d[s] < n){
if(x == t){
flow += augment();
x = s;
}
bool ok = false;
for(int &v = cur[x]; v != -1; v = next[v]){
edge& e = edges[v];
if(e.cap > e.flow && d[x] == d[e.to] + 1){
ok = true;
pre[x = e.to] = v;
break;
}
}
if(!ok){
int m = n - 1;
for(int v = head[x]; v != -1; v = next[v]){
edge & e = edges[v];
if(e.cap > e.flow) m = min(m,d[e.to]);
}
if(--num[d[x]] == 0) break;
num[d[x]=m+1]++;
cur[x] = head[x];
if(x != s) x = edges[pre[x]].from;
}
}
return flow;
}
} solver;
int N,M;
int a,b,w;
int main(void)
{
//freopen("input.txt","r",stdin);
scanf("%d %d", &N,&M);
solver.init(N + 2);
int s = 0, t = N + 1;
for(int i = 1 ; i <= N; ++i){
scanf("%d %d", &a, &b);
solver.addedge(s,i,a);
solver.addedge(i,t,b);
}
for(int i = 0; i < M; ++i){
scanf("%d %d %d", &a, &b,&w);
solver.addedge(a,b,w);
solver.addedge(b,a,w);
}
printf("%d\n",solver.maxflow(s,t));
return 0;
}