A1046 Shortest Distance (20 分)
The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits.
Input Specification:
Each input file contains one test case. For each case, the first line contains an integer N (in [3,105]), followed by N integer distances D1 D2 ⋯ DN , where Di is the distance between the i-th and the (i+1)-st exits, and DN is between the N-th and the 1st exits. All the numbers in a line are separated by a space. The second line gives a positive integer M (≤104 ), with M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to N. It is guaranteed that the total round trip distance is no more than 107 .
Output Specification:
For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.
Sample Input:
5 1 2 4 14 9
3
1 3
2 5
4 1
Sample Output:
3
10
7
错误思路
测试点2段错误,开大数组后超时,考虑简化时间复杂度。
//test1
long long int distances[10000];
int q[10000][2];
int short_dis[10000];
int main()
{
int n;
int m;
int temp[2] = { 0 };
int t1;
int t2;
scanf_s("%d", &n);
for (int i = 0; i < n; i++)
{
scanf_s("%d", &distances[i]);
}
scanf_s("%d", &m);
for (int i = 0; i < m; i++)
{
temp[0] = 0;
temp[1] = 0;
scanf_s("%d%d", &q[i][0], &q[i][1]);
t1 = max(q[i][0], q[i][1]);
t2 = min(q[i][0], q[i][1]);
while (t1 != t2)
{
temp[0] += distances[t1 - 1];
if (t1 == n)
{
t1 = 1;
}
else
{
t1++;
}
}
t1 = max(q[i][0], q[i][1]);
while (t1 != t2)
{
temp[1] += distances[t1 - 2];
t1--;
}
printf_s("%d\n", min(temp[0], temp[1]));
}
return 0;
}
正确思路
在输入时就累加计算当前点到1点的距离(把1看成原点参照点)
因此两端距离为:
1.dis[i]-dis[j]
2.sum-(dis[i]-dis[j])
for (int i = 0; i < n; i++)
{
scanf_s("%d", &dis[i]);
sum += dis[i];
dis[i] = sum;
}
完整代码
int dis[10000];
int dis_1[10000] = { 0 };
int sum = 0;
int q[2];
int main()
{
int n;
int m;
int temp[2];
scanf_s("%d", &n);
for (int i = 0; i < n; i++)
{
scanf_s("%d", &dis[i]);
sum += dis[i];
dis[i] = sum;
}
scanf_s("%d", &m);
for (int i = 0; i < m; i++)
{
scanf_s("%d%d", &q[0], &q[1]);
if (q[0] == 1)
{
temp[0] = dis[q[1] - 2];
}
else if (q[1] == 1)
{
temp[0] = dis[q[0] - 2];
}
else
{
temp[0] = abs(dis[q[0] - 2] - dis[q[1] - 2]);
}
temp[1] = sum - temp[0];
printf_s("%d\n", min(temp[0], temp[1]));
}
return 0;
}