问题 E: 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.

输入

Each input file contains one test case. For each case, the first line contains an integer N (in [3, 10 5 ]), followed by N integer distances D 1  D 2  ... D N , where D i  is the distance between the i-th and the (i+1)-st exits, and D N  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 (<=10 4 ), 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 10 7 .

输出

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

样例输入

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

样例输出

3
10
7

// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//


#pragma once


#include "targetver.h"


#include <stdio.h>
#include <tchar.h>
#include <stdlib.h>
#include <iostream>
using namespace std;




// TODO: 在此处引用程序需要的其他头文件


源文件

// ProbblemE.cpp: 定义控制台应用程序的入口点。
//


#include "stdafx.h"




int main()
{
int N = 0, M = 0;
int n[10000] = { 0 }, m1[1000] = { 0 }, m2[1000] = { 0 }, result[1000]={ 0 }, min[1000] = {0};
cin >> N;
for (int i = 0; i < N; i++) {
cin >> n[i];
}
cin >> M;
for (int i = 0; i < M; i++) {
cin >> m1[i] >> m2[i];
}


//顺着检测 m1--->m2
for (int i = 0; i < M; i++) {
result[1000] = { 0 };
if (m2[i] > m1[i]) {
int count = m2[i] - m1[i]; //个数
int start = m1[i] - 1; //从m1[i]开始 
for (int j = 0; j < count; j++) {
result[i] += n[start++];
}
}
else {
//分成两段
int start1 = m1[i] - 1;
int end1 = N;
int count = end1 - start1;
for (int j = 0; j < count; j++) {
result[i] += n[start1++];
}
//第二段
if (m2[i] > 1) {
int count2 = m2[i] - 1;
for (int j = 0; j < count2; j++) {
result[i] += n[j];
}
}


}
min[i] = result[i];


}


//反着检测
for (int i = 0; i < M; i++) {
result[i] = { 0 };
if (m2[i] < m1[i]) {
int count = m1[i] - m2[i];
int start = m1[i] - 2;
for (int j = 0; j < count; j++) {
result[i] += n[start--];
}
}
else {//分两段
int count1 = m1[i] - 1;
for (int j = 0; j < count1; j++) {
result[i] += n[j];
}
int count2 = N - m2[i]+1;

for (int j = 0; j < count2; j++) {
int temp = N;
result[i] += n[--temp];
}




}


}


for (int i = 0; i < M; i++) {
if (min[i] > result[i]) {
min[i] = result[i];
}
cout << min[i] << endl;
}






system("pause");
    return 0;
}

结果


问题.没有  但是就是好麻烦。。。  数组的元素老是想不明白


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值