Luo Gu P1330 blockade dfs violence sunlight University

Topic: https://www.luogu.org/problemnew/show/P1330

Interpretations: ① each side of the point of connection, at least one must be selected.
② two points of each edge is connected, it can not be selected simultaneously.

Thus, it can be inferred that: each side there is only one point and it is connected is selected.

Thus, for a connected graph, or to only two sorting (because all can be dyed in one color selected from, may be selected from all dyed another color), or else Impossible!

FIG find each sub-communication, it dyed black and white, then the minimum value in the two staining, then the final summary, it

 

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
const int maxn = 1e4 + 5; // 常数小应该能过,10000^2还是可以的
vector<int> g[maxn];      //图
int col[maxn], vis[maxn]; //颜色,标记
int n, m, sum;

void dfs(int i, int color) {
    if (col[i] != -1 &&
        col[i] != color) { //节点的颜色已有,但是和本次颜色冲突,无解
        cout << "Impossible";
        exit(0);
    }
    if (col[i] == color) //节点的颜色已有,和本次颜色一致
        return;
    //节点未染色
    col[i] = color;                       //染色
    vis[i] = 1;                           //标记
    sum++;                                //记录总和
    for (int j = 0; j < g[i].size(); j++) //深搜,换颜色
        dfs(g[i][j], color ^ 1);
}

int main() {
    // freopen("data.txt", "r", stdin);
    int x, y;
    cin >> n >> m;
    for (int i = 1; i <= m; i++) { //建图
        cin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    int ans, t;
    ans = 0;
    memset(vis, 0, sizeof(vis));
    for (int i = 1; i <= n; i++)
        if (vis[i] == 0) { //没搜过的就搜
            sum = 0;
            memset(col, -1, sizeof(col));
            dfs(i, 0);
            t = 0;
            for (int i = 1; i <= n; i++) //记录一种颜色
                t += col[i] == 1;
            ans += min(t, sum - t); //取两种颜色数量最小的
        }
    cout << ans;

    return 0;
}

 

Solution to a problem source  https://www.luogu.org/problemnew/solution/P1330

Guess you like

Origin blog.csdn.net/qq_38861305/article/details/90213494