UVA 216 - Getting in Line
连接是:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=152
哟我AC了喔.就是用回溯法把每一种可能都找出来,然后看哪个最小。
View Code
1 #include <iostream> 2 #include <cmath> 3 using namespace std; 4 5 const int MAXNUM = 8; 6 struct Point{ 7 int x; 8 int y; 9 }; 10 11 bool visit[MAXNUM]; 12 Point node[MAXNUM], temp[MAXNUM], final[MAXNUM]; 13 14 double dist(Point a, Point b) { 15 int x = a.x - b.x; 16 int y = a.y - b.y; 17 return sqrt(x*x + y*y); 18 } 19 20 // feet, temp_feet, level, nodes[], temp[], visit[], final[] 21 void traverse(double& feet, double temp_feet, int level, int num) { 22 if (level == num){ 23 feet = temp_feet; 24 25 for (int i = 0; i < num; i++) 26 final[i] = temp[i]; 27 } 28 29 for (int i = 0; i < num; i++){ 30 if (!visit[i]){ 31 visit[i] = true; 32 temp[level] = node[i]; 33 double next_temp_feet = temp_feet; 34 if (level) 35 next_temp_feet += dist(temp[level-1], temp[level]); 36 37 if (feet >= next_temp_feet) 38 traverse(feet, next_temp_feet, level+1, num); 39 visit[i] = false; 40 } 41 } 42 } 43 44 int main(int argc, char *argv[]){ 45 int num, network_num = 1; 46 cout.setf(ios::fixed); 47 cout.precision(2); 48 49 while (cin >> num && num){ 50 for (int i = 0; i < num; i++) 51 cin >> node[i].x >> node[i].y; 52 53 double feet = 0.0; 54 for (int i = 0; i < num-1; i++) 55 feet += dist(node[i], node[i+1]); 56 57 traverse(feet, 0, 0, num); 58 cout << "**********************************************************" << endl; 59 60 cout << "Network #" << network_num << endl; 61 for (int i = 0; i < num-1; i++){ 62 cout << "Cable requirement to connect " << "("; 63 cout << final[i].x << "," << final[i].y << ") to ("; 64 cout << final[i+1].x << "," << final[i+1].y << ") is "; 65 cout << dist(final[i], final[i+1]) + 16 << " feet." << endl; 66 } 67 cout << "Number of feet of cable required is " << feet + 16*(num-1) << "." << endl; 68 network_num++; 69 } 70 return 0; 71 }
这里的东西都是自娱自乐的.我只是抱着构思算法的心态去做UVA的题.
我所有的code都不可能AC的.因为我就没想着让它能AC.