图的m着色问题(洛谷-P2819)

题目描述

给定无向连通图G和m种不同的颜色。用这些颜色为图G的各顶点着色,每个顶点着一种颜色。如果有一种着色法使G中每条边的2个顶点着不同颜色,则称这个图是m可着色的。图的m着色问题是对于给定图G和m种颜色,找出所有不同的着色法。

输入输出格式

输入格式:

对于给定的无向连通图G和m种不同的颜色,编程计算图的所有不同的着色法。

输出格式:

程序运行结束时,将计算出的不同的着色方案数输出。

输入输出样例

输入样例#1:

5 8 4
1 2
1 3
1 4
2 3
2 4
2 5
3 4
4 5

输出样例#1:
48

思路:图的着色问题模版题

源代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 5000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;

int m,n,k;
int G[N][N];
int color[N];
int res;
void dfs(int x) {
    if(x == n+1) {
        res++;
        return;
    }
    else {
        for(int i=1; i<=k; i++) {
            bool flag=false;
            for(int y=1; y<=x; y++) {
                if(G[x][y]==1 && color[y]==i) {
                    flag=true;
                    break;
                }
            }
            if(flag==true)
                continue;

            color[x]=i;
            dfs(x+1);
            color[x]=0;
        }
    }
}
char mp[N][N];
int main() {
    scanf("%d%d%d",&n,&m,&k);//n个点m条边k种颜色
    for(int i=1; i<=m; i++) {
        int x,y;
        scanf("%d%d",&x,&y);
        G[x][y] = 1;
        G[y][x] = 1;
    }
    dfs(1);
    printf("%d",res);
    return 0;
}

 

posted @ 2022-09-20 22:53  老程序员111  阅读(60)  评论(0)    收藏  举报