SCU 4522 寻找fly真迹(二分图染色)

题目链接:点击打开链接

题目大意:一个点可能为a、b、c三个值,字典序相邻的点之间必须有一条边,给出一些点组成的图,判定这个图是否合法。

解题思路:从反面考虑,没有连边的点对,一定是一个为a、一个为c,所以问题就转化成了二分图判定。但是要注意,染色之后,颜色相同的点之间必须有边,颜色不同的点之间不能有边。


#include <set>
#include <map>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
#define FIN freopen("in.txt", "r", stdin);
#define FOUT freopen("out.txt", "w", stdout);
#define lson l, mid, cur << 1
#define rson mid + 1, r, cur << 1 | 1
const int INF = 0x3f3f3f3f;
const int MAXN = 5e2 + 50;
const int MAXM = 1e6 + 50;
const int MOD = 1e9 + 7;

int n, m, color[MAXN];
bool mp[MAXN][MAXN], ans;

void dfs(int cur, int col)
{
    if (!ans)
        return;
    color[cur] = col;
    bool app = false;
    for (int i = 1; i <= n; i++)
        if (i != cur && mp[cur][i])
        {
            app = true;
            if (color[i] == 0)
                dfs(i, -col);
            else if (color[i] == col)
            {
                ans = false;
                return;
            }
        }
    if (!app)
        color[cur] = 0;
}

int main()
{
#ifndef ONLINE_JUDGE
    FIN;
#endif // ONLINE_JUDGE
    int tcase;
    scanf("%d", &tcase);
    while (tcase--)
    {
        scanf("%d%d", &n, &m);
        memset(mp, true, sizeof(mp));
        memset(color, 0, sizeof(color));
        for (int i = 0; i < m; i++)
        {
            int x, y;
            scanf("%d%d", &x, &y);
            mp[x][y] = mp[y][x] = false;
        }
        ans = true;
        for (int i = 1; i <= n; i++)
            if (color[i] == 0)
                dfs(i, 1);
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
                if (i != j && color[i] != 0 && color[j] != 0)
                {
                    if (color[i] == color[j] && mp[i][j]) //颜色相同必须相连
                        ans = false;
                    if (color[i] != color[j] && !mp[i][j]) //颜色不同不能相连
                        ans = false;
                }
        printf("%s\n", ans ? "Yes" : "No");
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值