题意:有n个城市m条路,每个城市里有A[i]个士兵,士兵可以留在自己的城市或者邻近的城市,最后是人数是否能为B[i]
思路:
入门最大流
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<map>
#include<set>
using namespace std;
typedef long long LL;
#define maxn 505
#define f(x) (x*1.0)
#define inf 0x3f3f3f3f
#define maxm 1005
#define lowbit(x) (x&(-x))
#define cheak(i) printf("%d ",i)
#define lson(x) (splay[x].son[0])
#define rson(x) (splay[x].son[1])
#define rfor(i,a,b) for(i=a;i<=b;++i)
#define lfor(i,a,b) for(i=a;i>=b;--i)
#define mem(a,b) memset(a,b,sizeof(a))
#define mec(a,b) memcpy(a,b,sizeof(b))
const double PAI=acos(-1.0);
struct node
{
int st,ed,num,t;
}s[maxn];
int tot1;
struct star
{
int next,to,sta,val,c,f;
}e[maxn*2];
int h[maxn],cur[maxn],gap[maxn],dep[maxn],pre[maxn];
int tot;
void add_edge(int a,int b,int c)
{
e[++tot].next=h[a];
e[tot].sta=a;
e[tot].to=b;
e[tot].c=c;
e[tot].f=0;
h[a]=tot;
e[++tot].next=h[b];
e[tot].sta=b;
e[tot].to=a;
e[tot].c=0;
e[tot].f=0;
h[b]=tot;
}
void start()
{
mem(h,-1);tot=1;
}
int sap(int st,int ed,int N)
{
int i,v;
mem(gap,0);mem(dep,0);
mec(cur,h);
int u=st;
pre[u]=-1;
gap[0]=N;
int ans=0;
while(dep[st]<N)
{
//--------------------第一部分
if(u==ed)
{
int Min=inf;
for(i=pre[u];i!=-1;i=pre[e[i^1].to])
if(Min>e[i].c-e[i].f)
Min=e[i].c-e[i].f;
for(i=pre[u];i!=-1;i=pre[e[i^1].to])
{
e[i].f+=Min;
e[i^1].f-=Min;
}
u=st;
ans+=Min;
continue;
}
//--------------------end
//--------------------第二部分
bool flag=0;
for(i=cur[u];i!=-1;i=e[i].next)
{
v=e[i].to;
if(e[i].c-e[i].f&&dep[v]+1==dep[u])
{
flag=1;
cur[u]=pre[v]=i;
break;
}
}
if(flag)
{
u=v;continue;
}
//--------------------end
//--------------------第三部分
int Min=N;
for(i=h[u];i!=-1;i=e[i].next)
if(e[i].c-e[i].f&&dep[e[i].to]<Min)
{
Min=dep[e[i].to];
cur[u]=i;
}
gap[dep[u]]--;
if(!gap[dep[u]])
return ans;
dep[u]=Min+1;
gap[dep[u]]++;
if(u!=st) u=e[pre[u]^1].to;
//--------------------end
}
return ans;
}
int A[maxn],B[maxn];
int ans[maxn][maxn];
int main()
{
int n,m,i,u,v;
mem(h,-1);tot=1;
int sum=0,sum1=0;
scanf("%d%d",&n,&m);
rfor(i,1,n) scanf("%d",&A[i]);
rfor(i,1,n) scanf("%d",&B[i]);
rfor(i,1,n) sum+=B[i],sum1+=A[i];
if(sum!=sum1)
{
printf("NO\n");
return 0;
}
rfor(i,1,n) add_edge(i,i+n,inf);
rfor(i,1,m)
{
scanf("%d%d",&u,&v);
add_edge(u,v+n,inf);
add_edge(v,u+n,inf);
}
int sta=2*n+1,ed=sta+1;
rfor(i,1,n)
{
add_edge(sta,i,A[i]);
add_edge(i+n,ed,B[i]);
}
if(sap(sta,ed,ed)==sum)
{
printf("YES\n");
rfor(i,1,n)
{
for(int j=h[i];j!=-1;j=e[j].next)
{
int v=e[j].to;
ans[i][v-n]=e[j].f;
}
}
rfor(i,1,n)
{
int j;
rfor(j,1,n)
printf("%d ",ans[i][j]);
printf("\n");
}
}
else printf("NO\n");
return 0;
}