【算法课作业】最小哈密顿回路
Filed in: 数据结构与算法 Add comments
老杨留的作业,折腾几个小时加上参考别人的终于写出来了,还是很弱啊。
效率貌似还可以,强化了分支定界的条件之后计算N=20的情况只需要十几秒。
好好体会一下~
#include <cstdlib> #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; #define N 15 int curLightestWeight = 1000000; int curDepth = 0; int curWeight = 0; int depth; int curCircle[N],bestCircle[N]; bool used[N]; int p[N][N]; void update(); void show(); void genGraphic(int maxWeight) { for(int i = 0;i < N;i++) { for(int j = 0;j < N;j++) { if(i == j) p[i][j] = 0; else p[i][j] = rand()%maxWeight + 1; } } for(int i = 0;i < N;i++) { for(int j = 0;j < N;j++) { cout<<p[i][j]<<" "; } cout<<endl; } } void MHC_recursion(int curVertex) { curCircle[curDepth] = curVertex; curDepth++; used[curVertex] = true; if(curWeight + (depth - curDepth) >= curLightestWeight) { curDepth--; used[curVertex] = false; return; } else if(curDepth == depth) { int thisWeight = p[curVertex][0]; curWeight += thisWeight; if(curWeight < curLightestWeight) { curLightestWeight = curWeight; update(); } curDepth--; used[curVertex] = false; curWeight -= thisWeight; return; } else { for(int i = 0;i < N;i++) { if(i == curVertex || used[i] == true) continue; int thisWeight = p[curVertex][i]; curWeight += thisWeight; MHC_recursion(i); curWeight -= thisWeight; } } used[curVertex] = false; curDepth--; return; } void update() { for(int i = 0;i < N;i++) bestCircle[i] = curCircle[i]; } void show() { for(int i = 0;i < N;i++) cout<<bestCircle[i]<<"-->"; cout<<bestCircle[0]<<endl; cout<<"The weight of the circle is "<<curLightestWeight<<"."<<endl; } void init() { curDepth = 0; curWeight = 0; curLightestWeight = 1000000; depth = N; } int main(int argc, char *argv[]) { genGraphic(9); init(); MHC_recursion(0); show(); system("PAUSE"); return EXIT_SUCCESS; }
十二月 30th, 2010 at 3:50 下午
没有注释的程序不叫程序~
一月 1st, 2011 at 4:07 下午
接受批评!