URAL - 1099 Work Scheduling(一般图最大匹配-带花树模板)
生活随笔
收集整理的這篇文章主要介紹了
URAL - 1099 Work Scheduling(一般图最大匹配-带花树模板)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目鏈接:點(diǎn)擊查看
題目大意:給出n個(gè)警衛(wèi),接下來給出數(shù)個(gè)關(guān)系,表示兩個(gè)警衛(wèi)可以互相配合,現(xiàn)在規(guī)定只有可以互相配合的警衛(wèi)才能留下來繼續(xù)工作,問最多能有多少個(gè)警衛(wèi)留下來工作,輸出匹配方案
題目分析:一般圖最大匹配問題,帶花樹算法,菜雞只會(huì)用模板,貼一個(gè)大佬的博客:
https://www.cnblogs.com/owenyu/p/6858508.html
拿了個(gè)模板,暫時(shí)湊活用吧,關(guān)于用法,solve會(huì)返回最大匹配數(shù),match[x]與x為有效匹配,對(duì)于這個(gè)題目,匹配完后set去重一波輸出即可
代碼:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cstring> #include<algorithm> #include<stack> #include<queue> #include<map> #include<set> #include<sstream> using namespace std;typedef long long LL;const int inf=0x3f3f3f3f;const int N=505;const int M=N*N*2;int n,m,que[M],ql,qr,pre[N],tim=0;struct edge {int v,nxt; }e[M];int h[N],tot=0;int match[N],f[N],tp[N],tic[N];int find(int x) {return f[x]==x?f[x]:f[x]=find(f[x]); }void addedge(int u,int v) {e[++tot]=(edge){v,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<=n;++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 Bint t=0;while(ql<=qr) {int x=que[ql++];for(int i=h[x],v=e[i].v;i;i=e[i].nxt,v=e[i].v) {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 solve() {int ans=0;for(int i=1;i<=n;i++)if(!match[i]&&aug(i))ans++;return ans; }void init() {tot=0;memset(match,0,sizeof(match));memset(tic,0,sizeof(tic));memset(h,0,sizeof(h)); }int main() { // freopen("input.txt","r",stdin);init();scanf("%d",&n);int u,v;while(scanf("%d%d",&u,&v)!=EOF){addedge(u,v);addedge(v,u);}solve();set<pair<int,int>>ans;for(int i=1;i<=n;i++)if(match[i])ans.insert(make_pair(min(i,match[i]),max(i,match[i])));printf("%d\n",2*ans.size());for(auto it:ans)printf("%d %d\n",it.first,it.second);return 0; }?
超強(qiáng)干貨來襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的URAL - 1099 Work Scheduling(一般图最大匹配-带花树模板)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1285E D
- 下一篇: HDU - 4687 Boke and