luogu2819_图的m着色问题

luogu2819_图的m着色问题

时空限制    1000ms/128MB

题目背景

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

题目描述

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

输入输出格式

输入格式:

第1行有3个正整数n,k 和m,表示给定的图G有n个顶点和k条边,m种颜色。顶点编号为1,2,…,n。接下来的k行中,每行有2个正整数u,v,表示图G 的一条边(u,v)。

输出格式:

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

输入输出样例

输入样例#1:

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

输出样例#1:

48

说明

n<=100;k<=2500;

在n很大时保证k足够大。

保证答案不超过20000。

代码

#include<iostream>
using namespace std;
const int N = 105;
int n,k,m,color[N],ans;
bool a[N][N];

bool check(int x){
	for (int i=1; i<x; i++)
		if (a[i][x] && color[i]==color[x]) return false;
	return true;
}

void dfs(int x){
	if (x>n) { ans++; return; }
	for (int i=1; i<=m; i++){	//遍历m种颜色
		color[x] = i;
		if (check(x)) dfs(x+1);
		color[x] = 0;
	}
}

int main(){
	cin>>n>>k>>m;
	for (int i=1,x,y; i<=k; i++){
		cin>>x>>y;
		a[x][y] = a[y][x] = true;
	}
	dfs(1);
	cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/WDAJSNHC/article/details/81346681