题意就是有n个模块,每个模块可以运行在两个核心上,A核心和B核心,相应的有一个花费,有一些模块如果不在一个核心上运行就会产生额外的花费
现在要求最小的花费是的所有模块都运行
建图如下:
每个模块点,源点与其连边,容量为A花费,在用其与汇点连边,容量为相应B花费
然后如果有某对模块之间不运行在一个核心上会产生额外的花费,就对这两点建双向边,容量都为那个额外的花费
然后就是最小割模型
为啥这样建图就行呢, 可以观察, 如果一对点,假设为u,v之间不运行在一个模块会产生花费
首先,每个点不是与源点的边就是与汇点的边在割中,假如我们的割是有(s, u) (v, t) ,那么显然(v,u)这条边必须割掉,否则 s->v->u->t构成一条路径
如果割是(s,u) (s,v) 那么u,v之间的双向边一条也不需要割掉。也就满足了题意
#include <iostream> #include <algorithm> #include <cstring> #include <string> #include <cstdio> #include <cmath> #include <queue> #include <map> #include <set> #define eps 1e-5 #define MAXN 22222 #define MAXM 1111111 #define INF 100000007 using namespace std; struct node { int v; // vtex int c; // cacity int f; // current f in this arc int next, r; }edge[MAXM]; int dist[MAXN], nm[MAXN], src, des, n; int head[MAXN], e; void add(int x, int y, int c) { edge[e].v = y; edge[e].c = c; edge[e].f = 0; edge[e].r = e + 1; edge[e].next = head[x]; head[x] = e++; edge[e].v = x; edge[e].c = 0; edge[e].f = 0; edge[e].r = e - 1; edge[e].next = head[y]; head[y] = e++; } void rev_BFS() { int Q[MAXN], h = 0, t = 0; for(int i = 1; i <= n; ++i) { dist[i] = MAXN; nm[i] = 0; } Q[t++] = des; dist[des] = 0; nm[0] = 1; while(h != t) { int v = Q[h++]; for(int i = head[v]; i != -1; i = edge[i].next) { if(edge[edge[i].r].c == 0 || dist[edge[i].v] < MAXN)continue; dist[edge[i].v] = dist[v] + 1; ++nm[dist[edge[i].v]]; Q[t++] = edge[i].v; } } } void init() { e = 0; memset(head, -1, sizeof(head)); } int maxflow() { rev_BFS(); int u; int total = 0; int cur[MAXN], rpath[MAXN]; for(int i = 1; i <= n; ++i)cur[i] = head[i]; u = src; while(dist[src] < n) { if(u == des) // find an augmenting path { int tf = INF; for(int i = src; i != des; i = edge[cur[i]].v) tf = min(tf, edge[cur[i]].c); for(int i = src; i != des; i = edge[cur[i]].v) { edge[cur[i]].c -= tf; edge[edge[cur[i]].r].c += tf; edge[cur[i]].f += tf; edge[edge[cur[i]].r].f -= tf; } total += tf; u = src; } int i; for(i = cur[u]; i != -1; i = edge[i].next) if(edge[i].c > 0 && dist[u] == dist[edge[i].v] + 1)break; if(i != -1) // find an admissible arc, then Advance { cur[u] = i; rpath[edge[i].v] = edge[i].r; u = edge[i].v; } else // no admissible arc, then relabel this vtex { if(0 == (--nm[dist[u]]))break; // GAP cut, Important! cur[u] = head[u]; int mindist = n; for(int j = head[u]; j != -1; j = edge[j].next) if(edge[j].c > 0)mindist = min(mindist, dist[edge[j].v]); dist[u] = mindist + 1; ++nm[dist[u]]; if(u != src) u = edge[rpath[u]].v; // Backtrack } } return total; } int nt, m; int main() { int u, v, w, A, B; scanf("%d%d", &nt, &m); src = nt + 1; des = nt + 2; n = des; init(); for(int i = 1; i <= nt; i++) { scanf("%d%d", &A, &B); add(src, i, A); add(i, des, B); } for(int i = 1; i <= m; i++) { scanf("%d%d%d", &u, &v, &w); add(u, v, w); add(v, u, w); } printf("%d\n", maxflow()); return 0; }