P4258-[WC2016]挑战NPC【带花树】
生活随笔
收集整理的這篇文章主要介紹了
P4258-[WC2016]挑战NPC【带花树】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
正題
題目鏈接:https://www.luogu.com.cn/problem/P4258
題目大意
給出nnn個球,mmm個籃筐,每個球都可以被放入一些特定的籃筐,每個球都要放,要求球的個數小于等于111的籃筐數量最多。
保證有解,輸出方案。
1≤T≤5,1≤n≤3m,1≤m≤1001\leq T\leq 5,1\leq n\leq 3m,1\leq m\leq 1001≤T≤5,1≤n≤3m,1≤m≤100
解題思路
額其實做題之前已經知道正解是帶花樹就簡單很多了。
每個籃筐我們開一個三個點的環,那么如果環上大于一個點唄匹配掉了那么這個環內就無法匹配了。
又因為一定有解所以肯定不會因為環上的匹配使答案更劣,所以這樣匹配出來的結果為ansansans那么答案就是ans?nans-nans?n。
但是有一個問題我們發現這樣跑的話每個球不一定都是匹配點,這樣會影響我們輸出方案。因為我們是找增廣路的做法,這種做法不會減少已經匹配了的點,所以我們如果優先跑球代表的點就不會有問題了。
code
#include<cstdio> #include<cstring> #include<algorithm> #include<queue> using namespace std; const int N=1010,M=2e5+10; struct node{int to,next; }a[M<<1]; int cnt,tot,T,n,m,e,ans,ls[N]; int dfn[N],pre[N],fa[N],match[N],tag[N]; queue<int> q; void addl(int x,int y){a[++tot].to=y;a[tot].next=ls[x];ls[x]=tot;a[++tot].to=x;a[tot].next=ls[y];ls[y]=tot;return; } int find(int x) {return (fa[x]==x)?(x):(fa[x]=find(fa[x]));} int LCA(int x,int y){++cnt;x=find(x);y=find(y);while(dfn[x]!=cnt){dfn[x]=cnt;x=find(pre[match[x]]);if(y)swap(x,y);}return x; } void Blossom(int x,int y,int lca){while(find(x)!=lca){pre[x]=y;y=match[x];if(tag[y]==2){tag[y]=1;q.push(y);}fa[x]=fa[y]=lca;x=pre[y];}return; } int Agu(int s){memset(tag,0,sizeof(tag));memset(pre,0,sizeof(pre));for(int i=1;i<=3*m+n;i++)fa[i]=i;while(!q.empty())q.pop();q.push(s);tag[s]=1;while(!q.empty()){int x=q.front();q.pop();for(int i=ls[x];i;i=a[i].next){int y=a[i].to;if(!tag[y]){tag[y]=2;pre[y]=x;if(!match[y]){for(int u=y,lst;u;u=lst)lst=match[pre[u]],match[u]=pre[u],match[pre[u]]=u;return 1;}tag[match[y]]=1;q.push(match[y]);}else if(tag[y]==1&&find(x)!=find(y)){int lca=LCA(x,y);Blossom(x,y,lca);Blossom(y,x,lca);}}}return 0; } int main() {scanf("%d",&T);while(T--){tot=ans=0;memset(ls,0,sizeof(ls));memset(match,0,sizeof(match));scanf("%d%d%d",&n,&m,&e);for(int i=1;i<=m;i++)addl(i*3-2,i*3-1),addl(i*3-1,i*3),addl(i*3,i*3-2);for(int i=1;i<=e;i++){int x,y;scanf("%d%d",&x,&y);addl(x+3*m,y*3);addl(x+3*m,y*3-1);addl(x+3*m,y*3-2);}for(int i=n+3*m;i>=1;i--)if(!match[i])ans+=Agu(i);printf("%d\n",ans-n);for(int i=1;i<=n;i++)printf("%d ",1+(match[3*m+i]-1)/3);putchar('\n');}return 0; }總結
以上是生活随笔為你收集整理的P4258-[WC2016]挑战NPC【带花树】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: P7099-[yLOI2020]灼【数学
- 下一篇: 二级路由器怎么设置如何设置二级路由器