题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=36707

思路:根据题意拆点建图即可。

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
#define MAXN 2222
#define inf 1<<30 struct Edge{
int v,cap,next;
}edge[MAXN*MAXN]; int n,m,p,NE,NV,vs,vt;
int head[MAXN]; void Insert(int u,int v,int cap)
{
edge[NE].v=v;
edge[NE].cap=cap;
edge[NE].next=head[u];
head[u]=NE++; edge[NE].v=u;
edge[NE].cap=;
edge[NE].next=head[v];
head[v]=NE++;
} int level[MAXN],gap[MAXN];
void bfs(int vt)
{
memset(level,-,sizeof(level));
memset(gap,,sizeof(gap));
level[vt]=;
gap[]++;
queue<int>que;
que.push(vt);
while(!que.empty()){
int u=que.front();
que.pop();
for(int i=head[u];i!=-;i=edge[i].next){
int v=edge[i].v;
if(level[v]!=-)continue;
level[v]=level[u]+;
gap[level[v]]++;
que.push(v);
}
}
} int cur[MAXN],pre[MAXN];
int SAP(int vs,int vt)
{
bfs(vt);
memset(pre,-,sizeof(pre));
memcpy(cur,head,sizeof(head));
int u=pre[vs]=vs,aug=inf,maxflow=;
gap[]=NV;
while(level[vs]<NV){
bool flag=false;
for(int &i=cur[u];i!=-;i=edge[i].next){
int v=edge[i].v;
if(edge[i].cap>&&level[u]==level[v]+){
flag=true;
aug=min(aug,edge[i].cap);
pre[v]=u;
u=v;
if(v==vt){
maxflow+=aug;
for(u=pre[u];v!=vs;v=u,u=pre[u]){
edge[cur[u]].cap-=aug;
edge[cur[u]^].cap+=aug;
}
aug=inf;
}
break;
}
}
if(flag)continue;
int minlevel=NV;
for(int i=head[u];i!=-;i=edge[i].next){
int v=edge[i].v;
if(edge[i].cap>&&level[v]<minlevel){
minlevel=level[v];
cur[u]=i;
}
}
if(--gap[level[u]]==)break;
level[u]=minlevel+;
gap[level[u]]++;
u=pre[u];
}
return maxflow;
} char map[][];
int dir[][]={{-,},{,},{,-},{,}}; int main()
{
while(~scanf("%d%d%d",&n,&m,&p)){
for(int i=;i<n;i++)scanf("%s",map[i]);
NE=;
vs=,vt=*n*m+,NV=*n*m+;
memset(head,-,sizeof(head));
for(int i=;i<n;i++){
for(int j=;j<m;j++){
if(map[i][j]=='~')continue;
for(int k=;k<;k++){
int x=i+dir[k][],y=j+dir[k][];
if(x<||x>=n||y<||y>=m)continue;
Insert(i*m+j++n*m,x*m+y+,inf);
}
if(map[i][j]=='*'){
Insert(vs,i*m+j+,);
Insert(i*m+j+,i*m+j++n*m,);
}
else if(map[i][j]=='.')Insert(i*m+j+,i*m+j++n*m,);
else if(map[i][j]=='@')Insert(i*m+j+,i*m+j++n*m,inf);
else if(map[i][j]=='#')Insert(i*m+j+,i*m+j++n*m,inf),Insert(i*m+j++n*m,vt,p);
}
}
printf("%d\n",SAP(vs,vt));
}
return ;
}
05-11 14:48