2011-05-26 20:17:56 6_7布线问题 测试数据 1 3 2 3 3 //Author:王子硕 Date:2011/5/26 //Description:布线问题 优先队列 分支限界 剪枝函数 广度优先 6_7 #include <iostream> #include <fstream> #include <algorithm> #include <functional> #include <queue> using namespace std; class Node{ public: Node(); Node(const Node &other); static int n; static int **data; void NextArr(int i){ swap(arrWire[i],arrWire[t]); }; void comput(); int dist(int k, int l); int t;//已排好前t个电路板 int *arrWire; int cost; bool operator<(const Node &other)const{ if (t + cost < other.t + other.cost) { return true; } else return false; } }; int Node::n = 0; int** Node::data = NULL; Node::Node(){ t = 0; cost = 0; arrWire = new int[n]; for(int i = 0; i <= n; ++i){ arrWire[i] = i; } } Node::Node(const Node &other){ t = other.t; cost = other.cost; arrWire = new int[n]; for (int i = 0; i <= n; ++i) { arrWire[i] = other.arrWire[i]; } } int Node::dist(int k, int l){ int posk = 1, posl = 1; for (int i = 1; i <= t; ++i) { if (arrWire[i] == k){posk = i;} if (arrWire[i] == l){posl = i;} } return abs(posk - posl); } void Node::comput(){ int i,j,sum = 0; for (i = 1; i <= t; ++i) { for (j = i + 1; j <= t; ++j) { int s = arrWire[i] > arrWire[j] ? arrWire[j] : arrWire[i]; int b = arrWire[i] < arrWire[j] ? arrWire[j] : arrWire[i]; sum += dist(arrWire[i],arrWire[j]) * data[s][b - s]; } } cost = sum; } class Wire{ public: Wire(int n, int **data){ this->n = n; this->data = data; best = INT_MAX; bestA = new int[n + 1]; for (int i = 1; i <= n; ++i) { bestA[i] = i; } }; void ArrWire(); int getBest(){return best;} int *getBestA(){return bestA;} protected: int n; int **data; int best;//最优费用 int *bestA;//最优排列 }; void Wire::ArrWire(){ priority_queue<Node> Heap; Node::n = this->n; Node::data = this->data; Node initial; Heap.push(initial); while(!Heap.empty()){ Node father = Heap.top(); Heap.pop(); if (father.t == n) { if (father.cost < best) { best = father.cost; for (int i = 1; i <= n; ++i) { bestA[i] = father.arrWire[i]; } } } for(int i = father.t + 1; i <= n; ++i){ Node ChildNode(father); ChildNode.t++; ChildNode.NextArr(i); ChildNode.comput(); if (ChildNode.cost <= best) { Heap.push(ChildNode); } } } } int main(){ ifstream in("input.txt"); ofstream out("output.txt"); #define in cin #define out cout int cases; in>>cases; for(int Case = 1; Case <= cases; ++Case){ int n; in>>n; int **c = new int *[n]; int i,j; for (i = 1; i < n; ++i) { c[i] = new int[n - i]; } for (i = 1; i <= n; ++i) { for (j = 1; j <= n - i; ++j) { in>>c[i][j]; } } Wire test(n,c); test.ArrWire(); out<<"Case #"<<Case<<": "<<test.getBest()<<endl; for (i = 1; i <= n; ++i) { out<<test.getBestA()[i]<<" "; } out<<endl; } return 0; }