UVA 216 - Getting in Line

题目大意:把所有点用一条线联通,求出所有这些线中长度最短的一条


解题思路:求出这些点的全排列,并计算它的长度,记录最短长度的那排列

#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;

int main() {
	int num, arr[10][2], brr[10], order[10], count = 0;
	while (scanf("%d", &num), num) {
		double min = 1000000;
		for (int i = 0; i < num; i++)
			scanf("%d%d", &arr[i][0], &arr[i][1]), brr[i] = i;

		do {
			double sum = 0;
			for (int i = 0; i < num - 1; i++) {
				int x = arr[brr[i]][0] - arr[brr[i + 1]][0];
				int y = arr[brr[i]][1] - arr[brr[i + 1]][1];
				sum += sqrt(x * x + y * y);
			}
			if (sum < min) {
				min = sum;
				for (int i = 0; i < num; i++)
					order[i] = brr[i];
			}
		} while (next_permutation(brr, brr + num)); //寻找出所有点的全排列中距离之和最小的序列并记录下来

		printf("**********************************************************\nNetwork #%d\n", ++count);
		for (int i = 0; i < num - 1; i++) {
			int x = arr[order[i]][0] - arr[order[i + 1]][0];
			int y = arr[order[i]][1] - arr[order[i + 1]][1];
			printf("Cable requirement to connect (%d,%d) to (%d,%d) is %.2f feet.\n", 
					arr[order[i]][0], arr[order[i]][1], arr[order[i + 1]][0], arr[order[i + 1]][1], sqrt(x * x + y * y) + 16.0);
		}
		printf("Number of feet of cable required is %.2f.\n", min + 16 * (num - 1));
	}
	return 0;
}


你可能感兴趣的:(UVA 216 - Getting in Line)