这道题,关键在于,告诉你,递归的效率可以很低!
先给出我的递归程序
//UVA1347Tour
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int MAXN = 1e3 + 10;
int n;
double x[MAXN], y[MAXN];
double d[MAXN][MAXN];
double dis[MAXN][MAXN];
double dp(int i, int j) {
int tmp = 0;
if(i < j) {
tmp = i; i = j; j = tmp;
}
if(i == n - 1) { d[i][j] = d[j][i] = dis[n - 1][n] + dis[n][j];
//printf("d = %lf\n", d[i][j]);
return d[i][j]; }
return d[i][j] = d[j][i] = min(dp(i + 1, j) + dis[i + 1][i], dp(i + 1, i) + dis[j][i + 1]);
}
int main() {
freopen("UVA1347out.txt", "w", stdout);
while(scanf("%d", &n) == 1) {
memset(dis, 0, sizeof(dis));
memset(d, 0, sizeof(d));
for(int i = 1; i <= n; i++) scanf("%lf%lf", &x[i], &y[i]);
for(int i = 1; i <= n; i++)
for(int j = i + 1; j <= n; j++)
if(dis[i][j] != 0) continue;
else dis[i][j] = dis[j][i] = sqrt((x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]));
//计算两点间欧氏距离
//for(int i - )
printf("%.2lf\n", dp(2, 1) + dis[2][1]);
/*for(int i = 1; i <= n; i++) {
for(int j = i + 1; j <= n; j++) {
printf("%4lf ", dis[j][i]);
}
printf("\n");
}*/
}
}
/*
3
1 1
2 3
3 1
4
1 1
2 3
3 1
4 2
*/
虽然udebug的数据过了,但交上去3s都没跑完,直接T
所以要强行改成循环
下面是AC程序
//UVA1347Tour
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int MAXN = 1e3 + 10;
int n;
double x[MAXN], y[MAXN];
double d[MAXN][MAXN];
double dis[MAXN][MAXN];
int main() {
//freopen("UVA1347out.txt", "w", stdout);
while(scanf("%d", &n) == 1) {
memset(dis, 0, sizeof(dis));
memset(d, 0, sizeof(d));
for(int i = 1; i <= n; i++) scanf("%lf%lf", &x[i], &y[i]);
for(int i = 1; i <= n; i++)
for(int j = i + 1; j <= n; j++)
if(dis[i][j] != 0) continue;
else dis[i][j] = dis[j][i] = sqrt((x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]));
//计算两点间欧氏距离
for(int i = n - 1; i >= 2; i--) {
for(int j = 1; j < i; j++) {
if(i == n - 1) d[i][j] = dis[i][n] + dis[j][n];
else d[i][j] = min(d[i + 1][j] + dis[i + 1][i], d[i + 1][i] + dis[j][i + 1]);
}
}
printf("%.2lf\n", d[2][1] + dis[2][1]);
/*for(int i = 1; i <= n; i++) {
for(int j = i + 1; j <= n; j++) {
printf("%4lf ", dis[j][i]);
}
printf("\n");
}*/
}
}
/*
3
1 1
2 3
3 1
4
1 1
2 3
3 1
4 2
*/