题面
https://www.luogu.org/problemnew/show/P3356
题解
拆点+费用流
alpq654321讲过。
#include<cstdio> #include<cstring> #include<iostream> #include<vector> #include<queue> #define N 5000 #define INF 1000000007 #define T (2*n*m+1) #define S 0 #define LL long long #define ri register int using namespace std; int n,m,k,opt; struct graph { vector<int> to,w,c; vector<int> ed[N]; LL dis[N]; int cur[N]; bool vis[N]; void add_edge(int a,int b,int aw,int ac) { to.push_back(b); w.push_back(aw); c.push_back(ac); ed[a].push_back(to.size()-1); to.push_back(a); w.push_back(0); c.push_back(-ac); ed[b].push_back(to.size()-1); } bool spfa() { memset(dis,-0x3f,sizeof(dis)); memset(vis,0,sizeof(vis)); queue<int> q; dis[S]=0;q.push(S);vis[S]=1; while (!q.empty()) { int x=q.front(); q.pop(); for (ri i=0;i<ed[x].size();i++) { int e=ed[x][i]; if (dis[to[e]]<dis[x]+c[e] && w[e]) { dis[to[e]]=dis[x]+c[e]; if (!vis[to[e]]) vis[to[e]]=1,q.push(to[e]); } } vis[x]=0; } return dis[T]>-INF; } int dfs(int x,int lim) { if (x==T || !lim) return lim; LL sum=0; vis[x]=1; for (ri &i=cur[x];i<ed[x].size();i++) { int e=ed[x][i]; if (dis[x]+c[e]==dis[to[e]] && w[e] && !vis[to[e]]) { int f=dfs(to[e],min(lim,w[e])); w[e]-=f; w[1^e]+=f; lim-=f; sum+=f; if (!lim) return sum; } } return sum; } LL zkw() { LL ret=0; while (spfa()) { memset(vis,0,sizeof(vis)); memset(cur,0,sizeof(cur)); ret+=dfs(S,INF)*dis[T]; } return ret; } void print(int col,int tn) { if (tn==n*m) return; int now=n*m+tn; for (ri i=0;i<ed[now].size();i++) { int e=ed[now][i]; if (e%2==1) continue; if (c[e]==1 && w[e]==0 || c[e]==0 && w[e]<INF) { w[e]++; printf("%d %d ",col,to[e]-tn==1?1:0); print(col,to[e]); return; } } } } G; int id1(int x,int y) {return (x-1)*m+y;} int id2(int x,int y) {return n*m+(x-1)*m+y;} int main() { scanf("%d",&k); scanf("%d %d",&n,&m); swap(n,m); for (ri i=1;i<=n;i++) { for (ri j=1;j<=m;j++) { scanf("%d",&opt); if (opt!=1) { G.add_edge(id1(i,j),id2(i,j),INF,0); if (opt==2) G.add_edge(id1(i,j),id2(i,j),1,1); } } } for (ri i=1;i<=n;i++) { for (ri j=1;j<=m;j++) { if (i+1<=n) G.add_edge(id2(i,j),id1(i+1,j),INF,0); if (j+1<=m) G.add_edge(id2(i,j),id1(i,j+1),INF,0); } } G.add_edge(S,id1(1,1),k,0); G.add_edge(id2(n,m),T,k,0); int t=G.zkw(); for (ri i=1;i<=k;i++) G.print(i,1); return 0; }