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;
}

  

转载于:https://www.cnblogs.com/tyty-Somnuspoppy/p/7589040.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值