BZOJ 1565: [NOI2009]植物大战僵尸

时间:2021-12-08 20:32:00

拓扑+最小割

想画图解释的。。。可是画图不太好用啊

不如一起来膜神犇吧!


#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#define wz(x,y) ((x-1)*m+y)
#define INF 2e9
#define maxn 610
using namespace std;

int read()
{
int a=0,f=1;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9'){a=a*10+c-'0';c=getchar();}
return a*f;
}

struct edge{int to,v;};
vector<edge>e;
vector<int>e1[maxn],G[maxn];
int n,m,s,t,sum;
int rd[maxn],v[maxn],d[maxn],cur[maxn],score[maxn];

void add(int x,int y,int v)
{
e.push_back((edge){y,v});
G[x].push_back(e.size()-1);
e.push_back((edge){x,0});
G[y].push_back(e.size()-1);
}

void topo()
{
queue<int>q;
for(int i=1;i<=n*m;++i)
if(!rd[i]) q.push(i),v[i]=1;
while(!q.empty())
{
int x=q.front();q.pop();
for(int i=0;i<e1[x].size();++i)
if(--rd[e1[x][i]]==0) q.push(e1[x][i]),v[e1[x][i]]=1;
}
}

int bfs()
{
queue<int>q;
memset(d,-1,sizeof(d));
d[s]=0,q.push(s);
while(!q.empty())
{
int x=q.front();q.pop();
if(x==t) return 1;
for(int i=0;i<G[x].size();++i)
{
edge t=e[G[x][i]];
if(t.v&&d[t.to]==-1)
{
d[t.to]=d[x]+1;
q.push(t.to);
}
}
}
return 0;
}

int dfs(int x,int a)
{
if(x==t||!a) return a;
int flow=0,f;
for(int i=0;i<G[x].size();++i)
{
int t=G[x][i];
if(d[e[t].to]==d[x]+1&&(f=dfs(e[t].to,min(a,e[t].v)))>0)
{
e[t].v-=f;
e[t^1].v+=f;
flow+=f;
a-=f;
if(!a) break;
}
}
if(!flow) d[x]=-1;
return flow;
}

int dinic()
{
int res=0;
while(bfs())
{
memset(cur,0,sizeof(cur));
res+=dfs(s,INF);
}
return res;
}

void build()
{
for(int i=1;i<=n*m;++i)
if(v[i])
if(score[i]>0) sum+=score[i],add(s,i,score[i]);
else if(score[i]<0) add(i,t,-score[i]);
}

int main()
{
//freopen("1565.in","r",stdin);
//freopen("1565.out","w",stdout);
n=read(),m=read();
s=0,t=n*m+1;
for(int i=1;i<=n;++i)
for(int j=1;j<=m;++j)
{
int x=read(),y;
score[wz(i,j)]=x;
if(j!=1)
{
e1[wz(i,j)].push_back(wz(i,j-1));
++rd[wz(i,j-1)];
add(wz(i,j-1),wz(i,j),INF);
}
int w=read();
while(w--)
{
x=read()+1,y=read()+1;
add(wz(x,y),wz(i,j),INF);
e1[wz(i,j)].push_back(wz(x,y));
++rd[wz(x,y)];
}
}
topo();
build();
printf("%d\n",sum-dinic());
return 0;
}
找了个标称拍了一下,调都没调就过了,开心

-----------------------------------------------

数据生成器

#include<cstdio>
#include<cstdlib>
#include<ctime>
using namespace std;

int main()
{
srand(time(0));
freopen("1565.in","w",stdout);
int n=20,m=30;
printf("%d %d\n",n,m);
for(int i=1;i<=n*m;++i)
{
int t=rand()%5+1,x=rand()%10000+1;
if(t<=2) x=-x;
int w=rand()%5+1;
printf("%d %d",x,w);
while(w--)
{
int x=rand()%n+1,y=rand()%m+1;
printf(" %d %d",x,y);
}
printf("\n");
}
return 0;
}