1046. Shortest Distance (20)

#include <iostream>
#include <cstdio>
#include <vector>
#include <cmath>
using namespace std;

#define N 100000
#define step 1000

int main(int argc, char **argv) {
	int n, m;
	int dist[N] = {};
	int ld[N/step] = {};
	cin >> n;
	
	int total = 0;
	int sd = 0, s = 0, si = 0;
	for(int i = 0; i < n; i ++) {
		scanf("%d", dist+i);
		
		total += dist[i];
		sd += dist[i];
		s ++;
		
		if(s == step) {
			ld[si++] = sd;
			sd = 0;
			s = 0;
		}
	}
			
	
	cin >> m;
	for(int i = 0; i < m; i ++) {
		int c1, c2;
		scanf("%d%d", &c1, &c2);
		c1 --;
		c2 --;
		
		if(c1 > c2)
			swap(c1, c2);
		
		int d = 0;
		if(c2 > c1) {
			int d1 = c1, d2 = c2-1;
			if(d2 - d1 < step) {
				for(int i = d1; i <= d2; i ++)
					d += dist[i];
			}
			else {
				int p1 = d1/step + 1;
				int p2 = d2/step;
				for(int i = d1; i < p1*step; i ++)
					d += dist[i];
				for(int i = p1; i < p2; i ++)
					d += ld[i];
				for(int i = p2*step; i <= d2; i ++)
					d += dist[i];
			}
		}
		if((d<<1) > total)
			d = total - d;
		
		printf("%d\n", d);
	}

	return 0;
}


以下是按照链接中提供的优化算法实现的代码,比我的累加要高效多了。

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

#define N 100001

int main()
{
	int dist[N] = {};
	int n;
	scanf("%d", &n);
	for(int i = 2; i <= n; i ++) {
		scanf("%d", &dist[i]);
		dist[i] += dist[i-1];
	}

	int total;
	scanf("%d", &total);
	total += dist[n];

	int m;
	scanf("%d", &m);
	for(int i = 0; i < m; i ++) {
		int c1, c2;
		scanf("%d%d", &c1, &c2);

		if(c1 > c2)
			swap(c1, c2);

		int d1 = dist[c2] - dist[c1];
		int d2 = total - d1;
		printf("%d\n", min(d1, d2));
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值