二分图的判定hihocoder1121 and hdu3478

这两个题目都是二分图的判定,用dfs染色比较容易写。

算法流程:

选取一个没有染色的点,然后将这个点染色,那么跟他相连的所有点一定是不同颜色的,所以,如果存在已经染过颜色的,如果和这个颜色相同的话,就说明不是二分图,否则,继续从这个点往下染。

hihocoder

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;

const int maxn = 10010;
vector<int> mp[maxn];
int color[maxn];
void init(int n)
{
    memset(color, -1, sizeof(color));
    for (int i = 1; i <= n; i++) mp[i].clear();
}
bool dfs(int u, int c)//用0和1分别表示两种颜色
{
    color[u] = c;
    for (int i = 0; i < mp[u].size(); i++)
    {
        if (color[mp[u][i]] == c) return false;
        if (color[mp[u][i]] == -1 && !dfs(mp[u][i], c ^ 1)) return false;
    }
    return true;
}
int main()
{
    int T, n, m;
    scanf("%d", &T);
    while (T--)
    {
        int u, v;
        scanf("%d%d", &n, &m);
        init(n);
        for (int i = 0; i < m; i++)
        {
            scanf("%d%d", &u, &v);
            mp[u].push_back(v);
            mp[v].push_back(u);
        }
        bool ans = true;
        for (int i = 1; i <= n; i++)
        {
            if (color[i] == -1 && !dfs(i, 0))
            {
                ans = false;
                break;
            }
        }
        printf("%s\n", ans ? "Correct" : "Wrong");
    }
    return 0;
}

hdu3478

#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;

const int maxn = 100010;
vector<int> mp[maxn];
int color[maxn];
void init(int n)
{
    memset(color, -1, sizeof(color));
    for (int i = 0; i < n; i++) mp[i].clear();
}
bool dfs(int u, int c)
{
    color[u] = c;
    for (int i = 0; i < mp[u].size(); i++)
    {
        if (color[mp[u][i]] == c) return false;
        if (color[mp[u][i]] == -1 && !dfs(mp[u][i], c ^ 1)) return false;
    }
    return true;
}
int main()
{
    int T, n, m, S, kase = 0;
    scanf("%d", &T);
    while (T--)
    {
        scanf("%d%d%d", &n, &m, &S);
        if (n == 1)
        {
            printf("Case %d: YES\n", ++kase);
            continue;
        }
        init(n);
        int u, v, cnt = 0;
        for (int i = 0; i < m; i++)
        {
            scanf("%d%d", &u, &v);
            mp[u].push_back(v);
            mp[v].push_back(u); 
        }
        bool flag = dfs(S, 0);
        if (flag)
            printf("Case %d: NO\n", ++kase);
        else
            printf("Case %d: YES\n", ++kase);
    }

    return 0;
}

 

posted @ 2016-01-07 20:37  Howe_Young  阅读(313)  评论(0编辑  收藏  举报