1. 程式人生 > >codeforces 862B B. Mahmoud and Ehab and the bipartiteness

codeforces 862B B. Mahmoud and Ehab and the bipartiteness

com set pac 並且 復雜 oid include ces http

http://codeforces.com/problemset/problem/862/B

題意:

給出一個有n個點的二分圖和n-1條邊,問現在最多可以添加多少條邊使得這個圖中不存在自環,重邊,並且此圖還是一個二分圖。

思路:

想得比較復雜了。。。。其實既然已經給出了二分圖並且有n-1條邊,那麽我們就一定可以用染色法對每一個點進行染色,從而將點劃分為兩個集合,然後從兩個集合中分別任意選擇一個點連邊就行了。

一開始考慮二分圖的基本屬性是不存在奇數條邊的環。。。並不需要這樣,因為兩個集合是分開的,從兩個中分別任意選擇一個連邊,是肯定不會造成同一集合中的兩點有邊相連的。

代碼:

 1 #include <stdio.h>
 2
#include <vector> 3 using namespace std; 4 5 vector<int> v[100005]; 6 bool vis[100005]; 7 8 int color[100005]; 9 10 void dfs(int s) 11 { 12 vis[s] = 1; 13 14 if (color[s] == 0) color[s] = 1; 15 16 for (int i = 0;i < v[s].size();i++) 17 { 18 int to = v[s][i]; 19 20
if (!vis[to]) 21 { 22 if (color[s] == 1) color[to] = 2; 23 else color[to] = 1; 24 25 vis[to] = 1; 26 dfs(to); 27 } 28 } 29 } 30 31 int main() 32 { 33 int n; 34 35 scanf("%d",&n); 36 37 for (int i = 0;i < n - 1
;i++) 38 { 39 int x,y; 40 41 scanf("%d%d",&x,&y); 42 43 v[x].push_back(y); 44 v[y].push_back(x); 45 } 46 47 dfs(1); 48 49 long long cnt1 = 0,cnt2 = 0; 50 51 for (int i = 1;i <= n;i++) 52 { 53 if (color[i] == 1) cnt1++; 54 else cnt2++; 55 } 56 57 printf("%I64d\n",cnt1 * cnt2 - (n - 1)); 58 59 return 0; 60 }

PS:記得要用long long,要不會wa。

codeforces 862B B. Mahmoud and Ehab and the bipartiteness