日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Relation(NOIP模拟赛)(二分图染色)

發布時間:2024/4/17 编程问答 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Relation(NOIP模拟赛)(二分图染色) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

原題:

Description

有n個人,編號為1àn,告訴你那些人之間是不友好的。現在,讓你將這n個人分成兩組,使得每一組之內的人是互相友好的,如果可以分成兩組,則輸出如何分組的,如果不可以分成兩組,那么,輸出“IMPOSSIBLE”。

Input

第一行兩個整數n和m,1<=n<=50000,0<=m<=500000,分別表示人數以及不友好的人的對數。以下m行每行兩個數a,b,表示a與b是不友好的。

Output

如果可以分成兩個組,則輸出一個方案,第一行為第一組的人的編號,第二行為第二組人的,按升序輸出。其中,方案的字典序必須要最小,所謂的方案字典序最小,就是第一行和第二行連接,組成的序列的字典序最小,如果有多種分配方法,取第一個組別人數最多的方案。如果不能分成兩組,輸出“IMPOSSIBLE”。

?

Sample Input(relation.in)

5 4

1 4

1 5

2 4

2 5

Sample Output(relation.out)

1 2 3

4 5

樣例解釋:

有兩種方案,1 2 3 和 1 2

??????????? 4 5???? 3 4 5

兩種方案的字典序相同,取第一組人數最多的方案,所以輸出方案一。

題目滿足:

40%的數據n<=1000

100%的數據n<=50000,m<=500000

時限 1s

這道題典型的二分圖染色(因為分成2組)

當然,根據題目,我們最后要SORT一下輸出

并且,方案字典序相同時,取第一組人數最多的方案

所以染色的時候盡量多分配1,不行再回溯修改

下面貼代碼

#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; struct edge{int to,next; }g[1000001]; int color[50001]; int head[50001],n,m; bool visit[50001]; int ans1[50001],ans2[50001],num=0,num1=0,num2=0; void ins(int x,int y){g[++num].next=head[x];head[x]=num;g[num].to=y;} void insw(int x,int y){ins(x,y);ins(y,x);} bool dfs(int x){visit[x]=true;for(int i=head[x];i;i=g[i].next){if(!visit[g[i].to]){color[g[i].to]=color[x]==1?0:1;visit[g[i].to]=true;if(!dfs(g[i].to))color[x]=color[x]==1?0:1;}else if(color[g[i].to]!=-1&&color[g[i].to]==color[x]){color[x]=color[x]==1?0:1;return false;}}return true; } int main(){freopen("relation.in","r",stdin);freopen("relation.out","w",stdout);memset(color,-1,sizeof(color));scanf("%d%d",&n,&m);for(int i=1;i<=m;i++){int x,y;scanf("%d%d",&x,&y);insw(x,y);}bool shuchu=false;for(int i=1;i<=n;i++){if(color[i]==-1){color[i]=1;if(!dfs(i)){printf("IMPOSSIBLE\n");shuchu=true;break;}}}if(!shuchu){for(int i=1;i<=n;i++)if(color[i]||color[i]==-1)ans1[++num1]=i; else ans2[++num2]=i;sort(ans1+1,ans1+num1+1);sort(ans2+1,ans2+num2+1);for(int i=1;i<num1;i++)printf("%d ",ans1[i]);printf("%d\n",ans1[num1]);for(int i=1;i<num2;i++)printf("%d ",ans2[i]);printf("%d\n",ans2[num2]);}fclose(stdin);fclose(stdout); }

?

轉載于:https://www.cnblogs.com/ghostfly233/p/6897562.html

總結

以上是生活随笔為你收集整理的Relation(NOIP模拟赛)(二分图染色)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。