1. 程式人生 > >Codeforces Round #360 (Div. 2)C. NP-Hard Problem

Codeforces Round #360 (Div. 2)C. NP-Hard Problem

並且 pri baidu code int str 兩個 printf 染色

題意:給出一個無向圖,問是否可以是二分圖,

思路:染色就行了,二分圖又稱作二部圖,是圖論中的一種特殊模型。 設G=(V,E)是一個無向圖,如果頂點V可分割為兩個互不相交的子集(A,B),並且圖中的每條邊(i,j)所關聯的兩個頂點i和j分別屬於這兩個不同的頂點集(i in A,j in B),則稱圖G為一個二分圖。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int N=1e5+10;
 4 struct node{
 5     int to,next;
 6 }e[N*4];
 7 int head[N],tot;
8 void init(){ 9 memset(head,-1,sizeof(head)); 10 tot=0; 11 } 12 int n,m; 13 14 void add(int u,int v){ 15 e[tot].to=v;e[tot].next=head[u];head[u]=tot++; 16 } 17 int color[N],vis[N]; 18 set<int >a[3]; 19 int t=0; 20 void dfs(int u,int x){ 21 if(color[u]!=-1){ 22 if(color[u]!=x) t=1
;return ; 23 } 24 color[u]=x; 25 a[x].insert(u); 26 for(int i=head[u];i!=-1;i=e[i].next){ 27 dfs(e[i].to,x^1); 28 } 29 } 30 int main(){ 31 scanf("%d%d",&n,&m); 32 init(); 33 memset(color,-1,sizeof(color)); 34 int x,y; 35 for(int i=1;i<=m;i++){
36 scanf("%d%d",&x,&y); 37 add(x,y);add(y,x); 38 } 39 for(int i=1;i<=n;i++){ 40 if(color[i]==-1) dfs(i,1); 41 } 42 if(t) {cout<<-1<<endl;return 0;} 43 cout<<a[1].size()<<endl; 44 for(set<int >::iterator it=a[1].begin();it!=a[1].end();it++){ 45 printf("%d ",*it); 46 } 47 printf("\n"); 48 cout<<a[0].size()<<endl; 49 for(set<int >::iterator it=a[0].begin();it!=a[0].end();it++){ 50 printf("%d ",*it); 51 } 52 printf("\n"); 53 54 }

Codeforces Round #360 (Div. 2)C. NP-Hard Problem