源向每个小孩连边,容量是该小孩的初始糖数;
每个小孩向汇连边,容量是糖的平均数;
每个小孩想相邻的格子各连一条边,容量是1.
把图建好就很简单了
#include<stdio.h> #include<cstring> #include<math.h> #define inf 100000000 #define min(a,b) ((a)>(b))?(b):(a) using namespace std; int a,b,map[55][55]; int n,k,dist[3000],gap[3000],edgeHead[3000];//双向边 struct{ int v,cap,next,re; }edge[40000]; void addEdge(int u,int v,int ca){ edge[k].v=v; edge[k].cap=ca; edge[k].next=edgeHead[u]; edge[k].re=k + 1; //这个用来记录此边的反边 edgeHead[u]=k ++; edge[k].v=u; edge[k].cap=0; //这里是双向边 edge[k].next=edgeHead[v]; edge[k].re=k - 1; edgeHead[v]=k ++; } int dfs (int p , int limit) { if(p==n)return limit; for(int i=edgeHead[p];i!=0;i=edge[i].next){ int v = edge[i].v; if(dist[p]==(dist[v]+1) && edge[i].cap>0){ int t=dfs(v,min(limit , edge[i].cap)); if(t<0)return t;//没有增广路了 if(t>0)//更新流 { edge[i].cap-=t; edge[edge[i].re].cap+=t; return t; } } } int tmp=n+1; for(int i=edgeHead[p];i!=0;i=edge[i].next){ int v = edge[i].v; if(edge[i].cap>0) tmp=min(tmp,dist[v]+1); } if(--gap[dist[p]]==0 || dist[0]>n)return -1;//出现断层或回流已满 ++gap[dist[p]=tmp]; return 0; } int SAP() { gap[0]=n+1; int f = 0 , t=0; while (~(t=dfs(0,inf))) f+=t; return f; } int main(){ int i,j,v,e,sum; while(scanf("%d %d",&v,&e)!=EOF){ sum=0; memset(edgeHead,0,sizeof(edgeHead)); memset(dist,0,sizeof(dist)); memset (gap , 0 , sizeof(gap)); k=1; for(i=1;i<=v;i++) for(j=1;j<=e;j++){ scanf("%d",&map[i][j]); sum+=map[i][j]; } if(sum%(v*e)!=0){ printf("NO\n"); continue; } for(i=1;i<=v;i++) for(j=1;j<=e;j++){ addEdge(0,(i-1)*e+j,map[i][j]); addEdge((i-1)*e+j,v*e+1,sum/(v*e)); if(i-1>0) addEdge((i-1)*e+j,(i-1)*e-e+j,1); if(j-1>0) addEdge((i-1)*e+j,(i-1)*e+j-1,1); if(i+1<=v) addEdge((i-1)*e+j,(i-1)*e+e+j,1); if(j+1<=e) addEdge((i-1)*e+j,(i-1)*e+j+1,1); } n=v*e+1; int k=SAP(); if(k==sum) printf("YES\n"); else printf("NO\n"); } }