太空飞行计划问题
Description
W 教授正在为国家航天中心计划一系列的太空飞行。每次太空飞行可进行一系列商业性实验而获取利润。现已确定了一个可供选择的实验集合 E={E 1 ,E 2 ,…,E m },和进行这些实验需要使用的全部仪器的集合 I={I 1 ,I 2 ,…I n }。实验 E j 需要用到的仪器是 I 的子集 R j ⊆I。配置仪器 I k 的费用为 c k 美元。实验 E j 的赞助商已同意为该实验结果支付 p j 美元。W 教授的任务是找出一个有效算法,确定在一次太空飞行中要进行哪些实验并因此而配置哪些仪器才能使太空飞行的净收益最大。这里净收益是指进行实验所获得的全部收入与配置仪器的全部费用的差额。
对于给定的实验和仪器配置情况,编程找出净收益最大的试验计划。
Input
文件第 1 行有 2 个正整数 m和 n。m 是实验数,n 是仪器数。接下来的 m 行,每行是一个实验的有关数据。第一个数赞助商同意支付该实验的费用;接着是该实验需要用到的若干仪器的编号。最后一行的 n 个数是配置每个仪器的费用。
Output
将最佳实验方案输出到文件 output.txt 中。第 1 行是实验编号;第 2行是仪器编号;最后一行是净收益。
Sample Input
2 3
10 1 2
25 2 3
5 6 7
Sample Output
1 2
1 2 3
17
题目大意
给出许多完成后会有收益的实验,实验的完成依赖于若干花费得到的仪器。问最大收益。
题解
最大权闭合子图问题。
先默认为实验都完成。建图如下:
- 从源点向所有实验点连接一条容量为收益的边
- 仪器点向汇点连一条容量为费用的边
- 实验点向仪器点连一条容量无穷大的边
那么总收益减去这张图上的最小割就是答案。
对于求过最小割的残量网络遍历一遍,一端被访问一端未被访问的边就是割边。
由于没有spj删去了数据中的方案输出。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1000 + 10, M = 100000 + 10, inf = 0x3f3f3f3f;
struct Edge{
int fr, to, cap, flow;
}edg[M];
int n, m, tot, ans;
int hd[N], nxt[M];
int s, t;
int d[N], q[N], vis[N], dfn;
void insert(int u, int v, int w){
edg[tot].fr = u, edg[tot].to = v, edg[tot].cap = w;
nxt[tot] = hd[u]; hd[u] = tot;
tot++;
edg[tot].fr = v, edg[tot].to = u;
nxt[tot] = hd[v]; hd[v] = tot;
tot++;
}
void getit(int a){
int w;
scanf("%d", &w);
ans += w;
insert(s, a, w);
int c;
for(;;){
do c = getchar();
while(c == ' ');
ungetc(c,stdin);
if(c == 10 || c == 13) break;
scanf("%d", &w);
insert(a, m + w, inf);
}
}
void init(){
scanf("%d%d", &m, &n);
memset(hd, -1, sizeof(hd));
s = 0, t = n + m + 1;
for(int i = 1; i <= m; i++)
getit(i);
int w;
for(int i = 1; i <= n; i++){
scanf("%d", &w);
insert(m + i, t, w);
}
}
bool bfs(){
int head = 1, tail = 1;
q[1] = s; d[s] = 0; vis[s] = ++dfn;
while(head <= tail){
int u = q[head++];
for(int i = hd[u]; i >= 0; i = nxt[i]){
Edge &e = edg[i];
if(vis[e.to] == dfn || e.cap <= e.flow) continue;
vis[e.to] = dfn;
q[++tail] = e.to;
d[e.to] = d[u] + 1;
}
}
return vis[t] == dfn;
}
int dfs(int x, int a){
if(x == t || a == 0) return a;
int f, flow = 0;
for(int i = hd[x]; i >= 0; i = nxt[i]){
Edge &e = edg[i];
if(d[e.to] == d[x] + 1 && (f = dfs(e.to, min(a, e.cap - e.flow))) > 0){
flow += f;
e.flow += f;
edg[i^1].flow -=f;
a -= f;
if(a == 0) break;
}
}
return flow;
}
void work(){
int flow = 0;
while(bfs())
flow += dfs(s, inf);
printf("%d\n", ans - flow);
}
int main(){
freopen("prog82.in", "r", stdin);
freopen("prog82.out", "w", stdout);
init();
work();
return 0;
}