https://ac.nowcoder.com/acm/contest/5666/I
题意:n个点m条边,每个点有一个度数,问能否保留一部分边使得满足每个点的度数。
思路:最大流是假算法,不过也能过。见这位大佬https://blog.csdn.net/qq_43497140/article/details/107302444
正解是一般图最大匹配,建图方法,每个点拆成度数个点,每条边拆成两个点,中间连一条边,分别连到所连的两个点的度数个点。
当是完美匹配,就输出yes。
用了这里的模板https://rqy.moe/Algorithms/flower-tree/
#include<bits/stdc++.h>
using namespace std;
const int N = 350;
const int M = N * N * 2;
int pre[N], nxt[M], to[M], n, cnt;
int mate[N], link[N], vis[N], fa[N];
int que[N], hd, tl;
void addEdge(int x, int y) {
nxt[cnt] = pre[x];
to[pre[x] = cnt++] = y;
}
int Find(int x) { return fa[x] == x ? x : fa[x] = Find(fa[x]); }
int ss[N], tim;
int LCA(int x, int y) {
++tim;
while (ss[x] != tim) {
if (x) { ss[x] = tim; x = Find(link[mate[x]]); }
swap(x, y);
}
return x;
}
void Flower(int x, int y, int p) {
while (Find(x) != p) {
link[x] = y;
fa[y = mate[x]] = fa[x] = p;
if (vis[y] == 1) vis[que[tl++] = y] = 2;
x = link[y];
}
}
bool match(int x) {
hd = tl = 0;
for (int i = 1; i <= n; ++i) vis[fa[i] = i] = 0;
vis[que[tl++] = x] = 2;
while (hd < tl) {
x = que[hd++];
for (int i = pre[x]; ~i; i = nxt[i]) {
int u = to[i];
if (!vis[u]) {
vis[u] = 1;
link[u] = x;
if (!mate[u]) {
while (x) {
x = mate[link[u]];
mate[mate[u] = link[u]] = u;
u = x;
}
return true;
} else
vis[que[tl++] = mate[u]] = 2;
} else if (vis[u] == 2 && Find(u) != Find(x)) {
int p = LCA(x, u);
Flower(x, u, p);
Flower(u, x, p);
}
}
}
return false;
}
int main() {
//freopen("input.in","r",stdin);
int n0,m,x,y,ans,a,b;
while(scanf("%d%d",&n0,&m)!=EOF)
{
ans=n=0;
cnt=0;
tim=0;
memset(ss,0,sizeof(ss));
memset(pre,-1,sizeof(pre));
memset(mate,0,sizeof(mate));
pair<int,int> node[N];
int d[N];
int sum=0;
for(int i=1;i<=n0;i++)
{
cin>>d[i];
sum+=d[i];
if(d[i]==1)node[i]=make_pair(++n,0);
else node[i]=make_pair(n+1,n+2),n+=2;
}
while (m--) {
scanf("%d%d", &a, &b);
x=++n;y=++n;
addEdge(x, y);
addEdge(y, x);
if (!mate[x] && !mate[y])
mate[mate[x] = y] = x, ++ans;
addEdge(x, node[a].first);
addEdge(node[a].first, x);
if (!mate[x] && !mate[node[a].first])
mate[mate[x] = node[a].first] = x, ++ans;
if(node[a].second)
{
addEdge(x, node[a].second);
addEdge(node[a].second, x);
if (!mate[x] && !mate[node[a].second])
mate[mate[x] = node[a].second] = x, ++ans;
}
addEdge(node[b].first, y);
addEdge(y, node[b].first);
if (!mate[node[b].first] && !mate[y])
mate[mate[node[b].first] = y] = node[b].first, ++ans;
if(node[b].second)
{
addEdge(node[b].second, y);
addEdge(y, node[b].second);
if (!mate[node[b].second] && !mate[y])
mate[mate[node[b].second] = y] = node[b].second, ++ans;
}
}
for (int i = 1; i <= n; ++i)
if (!mate[i] && match(i))
++ans;
if(ans*2==n)puts("Yes");
else puts("No");
}
return 0;
}