回溯法--圖的m著色問題
阿新 • • 發佈:2022-05-20
題目描述
給定無向連通圖G(N,E),含有n個結點,k條邊。現在有m種顏色,現在要給n個結點塗色,要求相鄰結點不同色。求共有多少種塗色方案。
輸入第一行3個整數n,k,m;
接下來k行,每行兩個數,u,v表示u,v結點有一條無向邊。
輸出2行
第一行一個整數x表示方案數。
題目思路
- 遍歷每一種染色方法
題目程式碼
/* 3 3 3 1 2 1 3 2 3 6 */ #include <iostream> using namespace std; const int N = 10; int n; // 圖的頂點數 int m; // 可用顏色數 int a[N][N]; // 圖的鄰接矩陣 int x[N]; // 當前解 long long sum; // 當前已找到的可m著色方案數 bool Ok(int k) { for(int j = 1; j <= n; j ++ ) if((a[k][j] == 1) && x[j] == x[k]) return false; return true; } void Backtrack(int t) { if(t > n) { sum ++; for(int i = 1; i <= n; i ++ ) cout << x[i] << " "; cout << endl; } else { for(int i = 1; i <= m; i ++ ) { x[t] = i; if(Ok(t)) Backtrack(t + 1); x[t] = 0; } } } int main() { int e; cin >> n >> e >> m; for(int i = 1; i <= e; i ++ ) { int start, end; cin >> start >> end; a[start][end] = a[end][start] = 1; } Backtrack(1); cout << sum << endl; return 0; }