PAT A1046 Shortest Distance
Sample Input:
5 1 2 4 14 9
3
1 3
2 5
4 1
Sample Output:
3
10
7
-
思路1:
由于路线是一个环,即一维的,可以点1为源点,用一个数组d记录其余各点到1的距离,求出总长度sum,任一两点间的距离只有两种情况:
a.正向:d[e1]-d[e2]
b.绕一圈:sum - 正向 -
code1:
#include <stdio.h>
#include <cmath>
#include <iostream>
using namespace std;
const int maxn = 100010;
int n, m; //n:路数 m;两点数
int len[maxn], d[maxn] = {0}; //len:各点间的路程,d:存储各点到1的距离
int sum = 0; //总路程
int main(){
scanf("%d", &n);
for(int i = 1; i <= n; ++i){
scanf("%d", &len[i]);
sum += len[i];
d[i+1] = sum;
}
scanf("%d", &m);
int e1, e2;
for(int i = 0; i < m; ++i){
scanf("%d%d", &e1, &e2);
if(e2 < e1) swap(e1, e2); //保证e2再后面
int ans = d[e2] - d[e1];
int anti = sum - ans;
if(anti <= ans) ans = anti;
printf("%d", ans);
if(i != m-1) printf("\n");
}
return 0;
}
- T2 code:
#include <cmath>
#include <iostream>
using namespace std;
const int maxn = 100010;
int n, m; //n:路数 m;两点数
int len[maxn], d[maxn] = {0}; //len:各点间的路程,d:存储各点到1的距离
int sum = 0; //总路程
int main(){
scanf("%d", &n);
for(int i = 1; i <= n; ++i){
scanf("%d", &len[i]);
sum += len[i];
d[i+1] = sum;
}
scanf("%d", &m);
int e1, e2;
for(int i = 0; i < m; ++i){
scanf("%d%d", &e1, &e2);
if(e2 < e1) swap(e1, e2); //保证e2再后面
int ans = d[e2] - d[e1];
int anti = sum - ans;
if(anti <= ans) ans = anti;
printf("%d", ans);
if(i != m-1) printf("\n");
}
return 0;
}