CodeForces - 862B Mahmoud and Ehab and the bipartiteness(二分图染色)

Posted SomnusMistletoe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CodeForces - 862B Mahmoud and Ehab and the bipartiteness(二分图染色)相关的知识,希望对你有一定的参考价值。

题意:给定一个n个点的树,该树同时也是一个二分图,问最多能添加多少条边,使添加后的图也是一个二分图。

分析:

1、通过二分图染色,将树中所有节点分成两个集合,大小分别为cnt1和cnt2。

2、两个集合间总共可以连cnt1*cnt2条边,给定的是一个树,因此已经连了n-1条边,所以最多能连cnt1*cnt2-(n-1)条边。

3、注意输出。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define lowbit(x) (x & (-x))
const double eps = 1e-8;
inline int dcmp(double a, double b){
    if(fabs(a - b) < eps) return 0;
    return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 100000 + 10;
const int MAXT = 10000 + 10;
using namespace std;
int color[MAXN];
vector<int> G[MAXN];
bool dfs(int v, int c){
    color[v] = c;
    int len = G[v].size();
    for(int i = 0; i < len; ++i){
        if(color[G[v][i]] == c) return false;
        if(color[G[v][i]] == 0 && !dfs(G[v][i], -c)) return false;
    }
    return true;
}
int main(){
    int n;
    scanf("%d", &n);
    int a, b;
    for(int i = 0; i < n - 1; ++i){
        scanf("%d%d", &a, &b);
        G[a].push_back(b);
        G[b].push_back(a);
    }
    for(int i = 1; i <= n; ++i){
        if(color[i] == 0){
            dfs(i, 1);
        }
    }
    int cnt1 = 0;
    int cnt2 = 0;
    for(int i = 1; i <= n; ++i){
        if(color[i] == 1) ++cnt1;
        if(color[i] == -1) ++cnt2;
    }
    printf("%lld\n", (LL)cnt1 * (LL)cnt2 - (n - 1));
    return 0;
}

  

以上是关于CodeForces - 862B Mahmoud and Ehab and the bipartiteness(二分图染色)的主要内容,如果未能解决你的问题,请参考以下文章

codeforces 862B B. Mahmoud and Ehab and the bipartiteness

CodeForces - 862B Mahmoud and Ehab and the bipartiteness(二分图染色)

codeforces 862C. Mahmoud and Ehab and the xor

CodeForces - 766B Mahmoud and a Triangle

codeforces 766E Mahmoud and a xor trip

Codeforces Round #396 (Div. 2) C. Mahmoud and a Message DP