UVA-11080 Place the Guards(二分图染色)

来源:互联网 发布:怎样做网络宣传 编辑:程序博客网 时间:2024/05/22 03:13

UVA-11080

题意:用最少的士兵看守每条街道,但不可以相邻。

//代码参考自,,,#include<iostream>#include<cstdio>#include<cstring>#include<vector>using namespace std;const int maxn = 230;int n , m , c[maxn];vector<int> G[maxn];int color_now , color_all;bool dfs(int u){    color_all++;    if(c[u]==1)        color_now++;    for(int i = 0;i < G[u].size();i++)    {        int v = G[u][i];        if(c[v] == c[u]) return false;        if(c[v] == 3-c[u]) continue;        c[v] = 3 - c[u];        if(!dfs(v)) return false;    }    return true;}int main(){    int t;    cin>>t;    while(t--)    {        cin >> n >> m;        for(int i = 0;i < n;i++)            G[i].clear();        while(m--)        {            int a , b;            cin >> a >> b;            G[a].push_back(b);            G[b].push_back(a);        }        memset(c, 0, sizeof(c));        int res = 0;        for(int i = 0;i < n;i++)            if(!c[i])            {                color_all = color_now = 0;                c[i] = 1;                if(!dfs(i))                { res = -1; break; }                res += max(min(color_now, color_all-color_now), 1);            }        cout<< res <<endl;    }    return 0;}


0 0
原创粉丝点击