圖m着色問題

1 問題描述:ios

  給定無向圖,m種不一樣的顏色。使每一種着色法使G中每條邊的2個頂點不一樣顏色,若一個圖最少須要m種顏色才能使圖中每條邊鏈接的2個頂點着不一樣顏色,則成這個數m爲該圖的色數。求一個圖的色數m的問題稱爲圖的m可着色優化問題。算法

2 算法設計express

  用圖的鄰接矩陣a表示無向圖連通圖G=(V,E)。數組

  若存在相連的邊,則a[i][j] = 1,不然 a[i][j]=0.函數

  整數1,2,3.。。m用來表示爲一棵高度爲n+1的徹底m叉樹。優化

  解空間樹的第i層中每一結點都有m個兒子,每一個兒子相應於x[i]的m個可能的着色之一。ui

  第n+1層爲葉子結點。spa

 

在算法Backtrack,設計

  當i>n時,算法搜索至葉節點,獲得新的m着色方案,當前找到可m着色的方案樹增1.指針

  當i<=n時,當前擴展結點Z是解空間中的內部結點。該結點有x[i]=1,2,3.。。m共m個兒子結點。對當前擴展結點Z的每個兒子結點,由函數OK檢查其可行性,並以深度優先的方式遞歸地對可行子樹搜索,或剪去不可行子樹。

算法描述:

 

#include <iostream>
using namespace std; class Color{ friend int mColoring(int,int,int* *); private: bool Ok(int k); void Backtrack(int t); int n, m, * *a, * x; long sum; }; bool Color::Ok(int k) { for(int j=1;j<=n;j++) if((a[k][j] == 1)&&(x[j] == x[k])) return false; return true; } void Color::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 mColoring(int n,int m,int * * a) { Color X; X.n = n; X.m = m; X.a = a; X.sum = 0; int * p = new int [n+1]; for(int i=0;i<=n;i++) p[i] = 0; X.x = p; X.Backtrack(2); delete [] p; return X.sum; } int main() { int n,m; cout<<"請輸入想要肯定的m着色圖中m的值:"<<endl; cin>>m; cout<<endl<<"共有n個結點,n的值爲:"<<endl; cin>>n; int **arr = new int [n][n]; for(int i=0;i<n;i++) { cout<<"請輸入鏈接矩陣的第一行的數(0-1)"<<endl; for(int j=0;j<n;j++) { cin>>arr[i][j]; } } mColoring(n,m,arr); return 0; }

運行結果:

--------------------Configuration: test102501 - Win32 Debug-------------------- Compiling... test.cpp E:\study file\ACM\test102501\test.cpp(63) : error C2540: non-constant expression as array bound E:\study file\ACM\test102501\test.cpp(63) : error C2440: 'initializing' : cannot convert from 'int (*)[1]' to 'int ** ' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast Error executing cl.exe. test.obj - 2 error(s), 0 warning(s)

仍是不會指針數組的傳參...有空看看,mark一下

相關文章
相關標籤/搜索