题目大意:小明同学在玩植物大战僵尸游戏,现在轮到他控制僵尸打败植物。植物分布在一个m*n的矩形中。僵尸从右边向左边攻击,要想打到左边的植物,要先打到它右边的植物。有一些植物是可以保护其他植物的,僵尸不能进入植物保护的区域,否则就会死。打败植有可能失去资源,也有可能获得资源。求一种攻击植物的方法,使得僵尸获得的资源最多。
思路:先不考虑其他特殊的情况,一看到正权负权求最大就是最大权闭合图。但是有一个bug。在建图形成环的时候,只用最大流跑会把整个环都取到。但是因为植物的攻击速度比僵尸快,僵尸不能打环中的植物。所以建完图之后要跑一半遍TopSort,把图中的环去掉。
CODE:
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAX 1000
#define MAXE 500500
#define S 0
#define T (m * n + 1)
#define INF 0x7f7f7f7f
using namespace std;
int m,n,total_cost;
int src[MAX];
int head[MAX],_total = 1;
int next[MAXE],aim[MAXE],flow[MAXE];
int deep[MAX],_out[MAX];
bool v[MAX];
inline void Add(int x,int y,int f);
void TopSort();
inline bool BFS();
int Dinic(int x,int f);
int main()
{
cin >> m >> n;
for(int num,i = 1;i <= m * n; ++i) {
scanf("%d%d",&src[i],&num);
for(int x,y,j = 1;j <= num; ++j) {
scanf("%d%d",&x,&y);
Add(x * n + y + 1,i,INF);
Add(i,x * n + y + 1,0);
_out[x * n + y + 1]++;
}
if(i % n)
Add(i,i + 1,INF),Add(i + 1,i,0),_out[i]++;
}
TopSort();
for(int i = 1;i <= m * n; ++i)
if(v[i]) {
if(src[i] > 0)
Add(S,i,src[i]),Add(i,S,0);
else
Add(i,T,-src[i]),Add(T,i,0);
}
int max_flow = 0;
while(BFS())
max_flow += Dinic(S,INF);
cout << total_cost - max_flow << endl;
return 0;
}
inline void Add(int x,int y,int f)
{
next[++_total] = head[x];
aim[_total] = y;
flow[_total] = f;
head[x] = _total;
}
void TopSort()
{
static queue<int> q;
for(int i = 1;i <= m * n; ++i)
if(!_out[i]) q.push(i);
while(!q.empty()) {
int x = q.front(); q.pop();
v[x] = true;
if(src[x]>0)
total_cost += src[x];
for(int i = head[x];i;i = next[i])
if(!flow[i] && !--_out[aim[i]])
q.push(aim[i]);
}
}
inline bool BFS()
{
static queue<int> q;
while(!q.empty()) q.pop();
memset(deep,0,sizeof(deep));
deep[S] = 1;
q.push(S);
while(!q.empty()) {
int x = q.front(); q.pop();
for(int i = head[x];i;i = next[i])
if(!deep[aim[i]] && flow[i]) {
deep[aim[i]] = deep[x] + 1;
q.push(aim[i]);
if(aim[i] == T) return true;
}
}
return false;
}
int Dinic(int x,int f)
{
if(x == T) return f;
int temp = f;
for(int i = head[x];i;i = next[i])
if(deep[aim[i]] == deep[x] + 1 && flow[i] && temp) {
int away = Dinic(aim[i],min(temp,flow[i]));
if(!away) deep[aim[i]] = 0;
flow[i] -= away;
flow[i^1] += away;
temp -= away;
}
return f - temp;
}