思路见 PKU 1149,PIGS,构造网络流模型时,要注意合并节点和边
又是大神带我飞。。。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
#define REP( i, a, b ) for( int i = a; i < b; i++ )
#define FOR( i, a, b ) for( int i = a; i <= b; i++ )
#define CLR( a, x ) memset( a, x, sizeof a )
#define CPY( a, x ) memcpy( a, x, sizeof a )
const int maxn = 100 + 10;
const int maxm = 1000 + 10;
const int maxe = 10000 + 10;
const int INF = 1e9;
struct Edge{
int v, c, f;
int next;
Edge() {}
Edge(int v, int c, int f, int next) : v(v), c(c), f(f), next(next) {}
};
struct ISAP{
int n, s, t;
int num[maxn], cur[maxn], d[maxn], p[maxn];
int Head[maxn], cntE;
int Q[maxn], head, tail;
Edge edge[maxe];
void Init(int n){
this -> n = n;
cntE = 0;
CLR(Head, -1);
}
void Add(int u, int v, int c){
edge[cntE] = Edge(v, c, 0, Head[u]);
Head[u] = cntE++;
edge[cntE] = Edge(u, 0, 0, Head[v]);
Head[v] = cntE++;
}
void Bfs(){
CLR(d, -1);
CLR(num, 0);
d[t] = 0;
head = tail = 0;
Q[tail++] = t;
num[0] = 1;
while(head != tail){
int u = Q[head++];
for(int i = Head[u]; ~i; i = edge[i].next){
Edge &e = edge[i];
if(~d[e.v]) continue;
d[e.v] = d[u] + 1;
Q[tail++] = e.v;
num[d[e.v]] ++;
}
}
}
int Maxflow(int s, int t){
this -> s = s;
this -> t = t;
CPY(cur, Head);
Bfs();
int u = p[s] = s, flow = 0;
while(d[s] < n){
if(u == t){
int f = INF, neck;
for(int i = s; i != t; i = edge[cur[i]].v){
if(f > edge[cur[i]].c - edge[cur[i]].f){
f = edge[cur[i]].c - edge[cur[i]].f;
neck = i;
}
}
for(int i = s; i != t; i = edge[cur[i]].v){
edge[cur[i]].f += f;
edge[cur[i]^1].f -= f;
}
flow += f;
u = neck;
}
int ok = 0;
for(int i = cur[u]; ~i; i = edge[i].next){
Edge &e = edge[i];
if(e.c > e.f && d[e.v] + 1 == d[u]){
ok = 1;
cur[u] = i;
p[e.v] = u;
u = e.v;
break;
}
}
if(!ok){
int m = n - 1;
if(--num[d[u]] == 0) break;
for(int i = Head[u]; ~i; i = edge[i].next){
Edge &e = edge[i];
if(e.c - e.f > 0 && m > d[e.v]){
cur[u] = i;
m = d[e.v];
}
}
++num[d[u] = m + 1];
u = p[u];
}
}
return flow;
}
}solver;
int S, T, n, m, num[maxm], buy[maxn];
vector<int> pig_houses[maxm];
void input(){
FOR(i, 1, m) scanf("%d", &num[i]), pig_houses[i].clear();
FOR(i, 1, n){
int x, house;
scanf("%d", &x);
while(x--){
scanf("%d", &house);
pig_houses[house].push_back(i);
}
scanf("%d", &buy[i]);
}
}
void solve(){
S = 0, T = n + 1;
solver.Init(T + 1);
FOR(i, 1, m) REP(j, 0, pig_houses[i].size()){
if(j == 0) solver.Add(S, pig_houses[i][0], num[i]);
else solver.Add(pig_houses[i][j-1], pig_houses[i][j], INF);
}
FOR(i, 1, n) solver.Add(i, T, buy[i]);
printf("%d\n", solver.Maxflow(S, T));
}
int main()
{
//freopen("in.txt", "r", stdin);
while(~scanf("%d%d", &m, &n)){
input();
solve();
}
return 0;
}