CodeForces - 557D Vitaly and Cycle (二分图染色判定)

题意:给定一个无向图,问最少添加多少条边可以得到一个奇圈以及其方案数。
题解:是个简单的二分图染色判定
二分图的等价定义就是图中没有奇数边的环

1:一条边没有的时候,方案数为n*(n-1)*(n-2)/6
2: 每个联通分量至多只有2个点时 m*(n-2),m为包含两个点的联通分量个数
3:将每个二分图染为白色部分和黑色部分,那么每一种颜色块中,只需要再连一条边,即k*(k-1)/2


#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <set>
#include <map>
#include <sstream>
#include <cmath>
#include <stack>
#define LL long long
#define mod 1000000007
using namespace std;
const int maxn = 1e5 + 5;
const LL INF = 0x3f3f3f3f;
vector<int> vec[maxn];
int col[maxn];
int num[maxn][2];
int block[maxn];
bool dfs(int u, int c, int id){
    if(col[u] == c) return false;
    col[u] = c;
    num[id][c]++;
    block[id]++;
    for(int i=0; i<vec[u].size(); i++){
        int v = vec[u][i];
        if(col[v] == 1-c) continue;
        if(col[v] == c) return false;
        if(!dfs(v,1-c,id)) return false;
    }
    return true;
}
int main(){
    memset(col, -1, sizeof(col));
    int n,m;
    scanf("%d%d",&n,&m);
    if(m == 0){
        printf("3 %lld\n", 1LL*n*(n-1)*(n-2)/6);
        return 0;
    }
    for(int i=0; i<m; i++){
        int u,v;
        scanf("%d%d",&u,&v);
        vec[u].push_back(v);
        vec[v].push_back(u);
    }
    int cnt = 0;
    bool flag = false;
    for(int i=1; i<=n; i++){
        if(col[i] == -1){
            if(!dfs(i,1,cnt)){
                flag = true;
                break;
            }
            cnt++;
        }
    }
    if(flag){
        printf("0 1\n");
        return 0;
    }
    else {
        LL ans = 0;
        int tot = 0;
        for(int i=0; i<cnt; i++){
            if(block[i] == 2) tot++;
            else if(block[i] > 2){
                ans += (LL)num[i][0] * (num[i][0] - 1) / 2LL + (LL)num[i][1] * (num[i][1] - 1) / 2LL;
            }
        }
        if(ans == 0){
            printf("2 %lld\n",(LL)tot*(n-2));
        }
        else{
            printf("1 %lld\n",ans);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值