蓝桥杯 分考场 (图的着色)

  暴力:考察当前节点是否可以用已经用过的颜色填充,或者用一个新颜色填充。这题胡乱暴力应该是可以过的,但是暴力姿势不对会超时。

AC代码

#include <stdio.h>
#include <string.h>
#include <vector>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
const int MAXN = 100 + 5;
int G[MAXN][MAXN];
int room[MAXN][MAXN], cnt[MAXN];
int n, m, ans;

void dfs(int cur, int tol) {
    if(tol >= ans) return;
    if(cur > n) {
        ans = min(ans, tol);
        return;
    }

    for(int i = 0; i < tol; i++) {
        int f = 1;
        for(int j = 0; j < cnt[i]; j++) {
            int t = room[i][j];
            if(G[cur][t]) {
                f = 0;
                break;
            }
        }
        if(f) {
            room[i][cnt[i]++] = cur;
            dfs(cur+1, tol);
            --cnt[i];
        }
    }

    room[tol][cnt[tol]++] = cur;
    dfs(cur+1, tol+1);
    --cnt[tol];
}

int main() {
    while(scanf("%d%d", &n, &m) == 2) {
        memset(G, 0, sizeof(G));
        int x, y;
        for(int i = 0; i < m; i++) {
            scanf("%d%d", &x, &y);
            G[x][y] = G[y][x] = 1;
        }
        memset(cnt, 0, sizeof(cnt));
        ans = INF;
        dfs(1, 0);
        printf("%d
", ans);
    }
    return 0;
}

  如有不当之处欢迎指出!!

原文地址:https://www.cnblogs.com/flyawayl/p/9064565.html