# loj6225「网络流 24 题」火星探险问题（费用流）

xiaoxiao2021-02-28  2

#include <cstdio> #include <cstring> #include <queue> #include <algorithm> using namespace std; #define ll long long #define inf 0x3f3f3f3f #define N 2510 inline int read(){ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar(); return x*f; } int n,m,C,h[N],num=1,T,ans=0,path[N],dis[N],mp[40][40],tot=0; int dx[]={0,1},dy[]={1,0}; bool inq[N]; struct edge{ int to,next,w,c; }data[12100]; inline void add(int x,int y,int w,int c){ data[++num].to=y;data[num].next=h[x];h[x]=num;data[num].w=w;data[num].c=c; data[++num].to=x;data[num].next=h[y];h[y]=num;data[num].w=0;data[num].c=-c; } inline bool spfa(){ queue<int>q;memset(path,0,sizeof(path));memset(dis,128,sizeof(dis)); q.push(0);dis[0]=0;inq[0]=1; while(!q.empty()){ int x=q.front();q.pop();inq[x]=0; for(int i=h[x];i;i=data[i].next){ int y=data[i].to;if(!data[i].w) continue; if(dis[x]+data[i].c>dis[y]){ dis[y]=dis[x]+data[i].c;path[y]=i; if(!inq[y]) q.push(y),inq[y]=1; } } }return path[T]; } inline int id(int x,int y){return (x-1)*m+y;} inline void dfs(int x,int id){ if(x==tot) return; for(int i=h[x+tot];i;i=data[i].next){ if(i&1||!data[i^1].w) continue; int y=data[i].to;if(x%m==y%m) printf("%d 0\n",id); else printf("%d 1\n",id);data[i].w+=1;data[i^1].w-=1; dfs(y,id);return; } } int main(){ // freopen("a.in","r",stdin); C=read();m=read();n=read();tot=n*m; for(int i=1;i<=n;++i) for(int j=1;j<=m;++j) mp[i][j]=read(); for(int x=1;x<=n;++x) for(int y=1;y<=m;++y){ if(mp[x][y]==1) continue; add(id(x,y),id(x,y)+tot,inf,0); if(mp[x][y]==2) add(id(x,y),id(x,y)+tot,1,1); for(int k=0;k<2;++k){ int xx=x+dx[k],yy=y+dy[k]; if(xx>n||yy>m||mp[xx][yy]==1) continue; add(id(x,y)+tot,id(xx,yy),inf,0); } }add(0,1,C,0);T=tot<<1; while(spfa()){ int low=inf,now=T; while(path[now]) low=min(low,data[path[now]].w),now=data[path[now]^1].to; ans+=low;now=T; while(path[now]) data[path[now]].w-=low,data[path[now]^1].w+=low,now=data[path[now]^1].to; }for(int i=1;i<=ans;++i) dfs(1,i); return 0; }