1. 程式人生 > >洛谷P1330封鎖陽光大學題解

洛谷P1330封鎖陽光大學題解

題意

此題可以說是一個很裸的一個二分圖染色,但是比較不同的是,這個圖中可能是不聯通的,因此我們需要找到所有的聯通塊,然後一一選出每個聯通塊中黑塊與白塊中最小的個數,然後加入到最後的答案中去,也是很坑的一點。

然後就需要用到深搜來二分圖染色,就是如果當前顏色為白色,那接下來所遍歷到的點的顏色則一定要與當前顏色相反.

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <vector>
using namespace std;
const int maxn=10010;
int n,m,tot_1,tot_2,ans;
vector <int> e[1010];
int f[maxn];
void dfs(int u)
{
    for(int i = 1; i < e[u].size(); i++)
    {
        if (f[u] == f[e[u][i]])
        {
            cout<<"Impossible";
            exit(0);
        }
        if (!f[e[u][i]]) 
        {
            f[e[u][i]] = 3 - f[u];
            if(f[e[u][i]] == 1)
            tot_1++;
            else 
            tot_2++;
            dfs(e[u][i]);
        }
    }
}
int main()
{
    int x, y; 
    cin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        cin >> x >> y;
        e[x].push_back(y);
        e[y].push_back(x);;
    }
    for(int i = 1; i <= n; i++)
    if(!f[i])
    {
        f[i] = 1;
        tot_1 = 1;
        tot_2 = 0;
        dfs(i);
        tot_1 = min(tot_1,tot_2);
        ans += tot_1;
    }
    cout<<ans;
    return 0;
}