UVA11080 Place the Guards

微微发亮的传送门

这道题大体上就是对一个图进行染色,相邻的两个点不能被染上相同的颜色,那么对于图中的点,如果该点没被染色,就把它染色,同时向外扩展。每次染色一定就染完了一个连通块,所以最后要么所有点被染色,要么无解。最后选取用的比较少的颜色为答案。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 222;
vector<int> G[maxn];
int n, m, x, y, col[maxn];
bool dfs(int u, int &tot, int &cnt){
    tot += 1;
    if (col[u] == 1) cnt += 1;
    for (int i = 0; i < G[u].size(); i++){
        int v = G[u][i];
        if (col[u] == col[v]) return 0;
        if (!col[v]){
            col[v] = 3 - col[u];
            if (!dfs(v, tot, cnt)) return 0;
        }
    }
    return 1;
}
int main(){
    int cs;
    scanf("%d", &cs);
    while(cs--){
        scanf("%d%d", &n, &m);
        for (int i = 0; i <= n; i++) G[i].clear();
        for (int i = 0; i < m; i++){
            scanf("%d%d", &x, &y);
            G[x].push_back(y);
            G[y].push_back(x);
        }
        memset(col, 0, sizeof(col));
        int ans = 0;
        bool f = 1;
        for (int i = 0; i < n; i++){
            if (!col[i]){
                col[i] = 1;
                int cnt = 0, tot = 0;
                if (!dfs(i, tot, cnt)){
                    f = 0;
                    break;
                }
                if (tot == 1) ans += 1;
                else ans += min(cnt, tot - cnt);
            }
        }
        if (f) printf("%d\n", ans);
        else puts("-1");
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值