UVA11080- Place the Guards(二分图染色)

本文介绍了一种基于二分图染色的算法,用于解决最少士兵监视道路的问题。通过黑白染色确定最少的士兵数量,并确保士兵不相邻。文章详细展示了算法实现的代码,并考虑了多个连通块的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链


题意:放最少的士兵去监视所有的道路, 但士兵不可相邻,符合的话,就输出最少的士兵数,否则输出-1

思路:其实就是二分图染色,即黑白染色,然后选择黑白染色最少的那个颜色累加,但要注意可能有多个连通块,只要有一个连通块不符合的话,就不符合。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>

using namespace std;

const int MAXN = 205;

vector<int> g[MAXN];

int color[MAXN];
int v, e, cur, num;

bool bipartite(int u, int &cur, int &num) {
    num++;
    if (color[u] == 1) cur++;
    for (int i = 0; i < g[u].size(); i++) {
        int v = g[u][i]; 
        if (color[v] == color[u]) return false;
        if (!color[v]) {
            color[v] = 3 - color[u]; 
            if (!bipartite(v, cur, num)) return false;
        }
    }
    return true;
}

int main() {
    int cas;
    scanf("%d", &cas);
    while (cas--) {
        scanf("%d%d", &v, &e);    
        for (int i = 0; i < v; i++)
            g[i].clear();
        int a, b;
        for (int i = 0; i < e; i++) {
            scanf("%d%d", &a, &b); 
            g[a].push_back(b);
            g[b].push_back(a);
        } 

        int flag = 1;
        int ans = 0;
        memset(color, 0, sizeof(color));
        for (int i = 0; i < v; i++) {
            if (!color[i]) {
                num = cur = 0;
                color[i] = 1;
                if (!bipartite(i, cur, num)) { 
                    flag = 0;
                    break;
                }
                if (num == 1) ans++;
                else {
                    ans += min(cur, num - cur); 
                } 
            }
        } 

        if (flag)
            printf("%d\n", ans);
        else
            printf("-1\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值