题目描述:
花老师有一个农场,农场的花一共有 4 种颜色, 花老师不喜欢老旧的东西,所以,她希望每天种花的方案都不一样。特别地,她也觉得两种一样颜色的花种在相邻的位置会很无聊。现在,她想知道,一共有多少种花的方案。这里要注意的是,农场的种花的位置是不规则的。因此我们给出一对一对的相邻的位置的关系。
输入:
第一行两个数 N 和 M,表示种花的位置的个数和相邻的位置的对数
接下来 M 行,每行一组数 A, B 表示 A, B 相邻
接下来 M 行,每行一组数 A, B 表示 A, B 相邻
求染色方法数
代码:
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn=60;
int G[maxn][maxn],color[maxn],ans=0;
void graphColor(int n,int c);
bool check(int k);
int main()
{
//freopen("in.txt","r",stdin);
int n,m;
cin>>n>>m;
for(int i=1;i<=m;i++){
int x,y;
cin>>x>>y;
G[x][y]=1;
G[y][x]=1;
}
graphColor(n,4);
printf("%d\n",ans);
return 0;
}
void graphColor(int n,int c){
memset(color,0,sizeof(color));
int k=1;
while(k>=1){
color[k]++;
while(color[k]<=c)//选择颜色
if(check(k))break;
else color[k]++;
if(color[k]<=c&&k==n){//得到一个方案
ans++;
}
else if(color[k]<=c&&k<n){
k++;
}
else {//返回父节点
color[k]=0;
k--;
}
}
}
bool check(int k){
for(int i=1;i<k;i++)
if(G[i][k]==1&&color[i]==color[k])
return false;
return true;
}