A1046 Shortest Distance

Description

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

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

For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.

Sample Input Copy

5 1 2 4 14 9
3
1 3
2 5
4 1

Sample Output Copy

3
10
7

idea

  • sum存储一圈的距离
  • disc[i]存储结点1到结点i的距离(对dics数组预处理,查询最短距离需要多次用到该数据,否则在最坏的情况下10^5,会超时)
    ==》则t = disc[b-1] - disc[a - 1]为顺时针a到b的距离
    sum -t为逆时针a到b的距离
    其中,可能会有a > b,交换即可(反正a到b 和 b到a的距离一样
  • disc[0] = 0记得初始化

solution1(相当笨拙,而且超时/(ㄒoㄒ)/~~

#include <stdio.h>
int main(){
	int n, m, a, b;
	scanf("%d", &n);
	int d[n];
	for(int i = 0; i < n; i++)
		scanf("%d", d + i);
	scanf("%d", &m);
	while(m--){
		int d1 = 0, d2 = 0, i, mind;
		scanf("%d%d", &a, &b);
		if(a == b)
			mind = 0;
		else{
			i = a - 1;
			while(i != b-1){
				d1 += d[i];
				i = (++i) % n;
			}
			
			if(a - 2 < 0)
				i = a - 2 + n;
			else
				i = (a - 2) % n;
			while(i != b-1){
				d2 += d[i];
				i--;
				if(i < 0)
					i += n;
				else
					i %= n;
			}
			d2 += d[b-1];
			mind = d1 < d2 ? d1 : d2;
		}
		printf("%d", mind);
		if(m != 0)
			printf("\n");
	}
	return 0;
}

solution(优雅版

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

int main(){
	int n, m, a, b;
	scanf("%d", &n);
	int d[n], sum = 0, disc[n] = {0}, t;
	for(int i = 1; i < n + 1; i++){
		scanf("%d", d + i);
		sum += d[i];
		disc[i] = sum;
	}		
	scanf("%d", &m);
	while(m--){
		scanf("%d%d", &a, &b);
		if(a > b)
			swap(a, b);
		t = disc[b - 1] - disc[a - 1];
		printf("%d", min(t, sum - t));
		if(m != 0)
			printf("\n");
	}
	return 0;
}
posted @ 2022-01-05 20:06  Moliay  阅读(8)  评论(0编辑  收藏  举报