讲解:https://blog.csdn.net/qq_45458915/article/details/107306393
代码:
#include<cstdio>
#include<cctype>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=505;
const int maxm=maxn*maxn*2;
int que[maxm],ql,qr,pre[maxn],tim=0;
int h[maxn],ne[maxm],ver[maxm],tot=0;
int match[maxn],f[maxn],tp[maxn],tic[maxn];
int id[maxn][maxn],du[maxn];int cnt=0;
int find(int x) {
return f[x]==x?f[x]:f[x]=find(f[x]);
}
void add(int u,int v) {
ver[tot]=v;
ne[tot]=h[u];
h[u]=tot++;
}
int lca(int x,int y) {
for (++tim;;swap(x,y)) if (x) {
x=find(x);
if (tic[x]==tim) return x; else tic[x]=tim,x=pre[match[x]];
}
}
void shrink(int x,int y,int p) {
while (find(x)!=p) {
pre[x]=y,y=match[x];
if (tp[y]==2) tp[y]=1,que[++qr]=y;
if (find(x)==x) f[x]=p;
if (find(y)==y) f[y]=p;
x=pre[y];
}
}
bool aug(int s) {
for (int i=1;i<=cnt;++i) f[i]=i;
memset(tp,0,sizeof tp),memset(pre,0,sizeof pre);
tp[que[ql=qr=1]=s]=1; // 1: type A ; 2: type B
int t=0;
while (ql<=qr) {
int x=que[ql++];
for (int i=h[x],v=ver[i];i!=-1;i=ne[i],v=ver[i]) {
if (find(v)==find(x) || tp[v]==2) continue;
if (!tp[v]) {
tp[v]=2,pre[v]=x;
if (!match[v]) {
for (int now=v,last,tmp;now;now=last) {
last=match[tmp=pre[now]];
match[now]=tmp,match[tmp]=now;
}
return true;
}
tp[match[v]]=1,que[++qr]=match[v];
} else if (tp[v]==1) {
int l=lca(x,v);
shrink(x,v,l);
shrink(v,x,l);
}
}
}
return false;
}
int main() {
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(h,-1,sizeof h);
memset(match,0,sizeof match);
tot=0;cnt=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&du[i]);
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=du[i];j++)
{
id[i][j]=++cnt;
}
}
for (int i=1;i<=m;++i)
{
int x,y;
scanf("%d%d",&x,&y);
add(cnt+1,cnt+2);add(cnt+2,cnt+1);
for(int j=1;j<=du[x];j++)
{
add(cnt+1,id[x][j]);
add(id[x][j],cnt+1);
}
for(int j=1;j<=du[y];j++)
{
add(cnt+2,id[y][j]);
add(id[y][j],cnt+2);
}
cnt+=2;
}
int ans=0;
for (int i=1;i<=cnt;++i) ans+=(!match[i] && aug(i));//n都要改成cnt
if(ans*2==cnt) printf("Yes\n");
else printf("No\n");
}
return 0;
}