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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章