1. 程式人生 > >ACM-ICPC 2018 北京賽區網路預賽 80 Days

ACM-ICPC 2018 北京賽區網路預賽 80 Days

時間限制:1000ms

單點時限:1000ms

記憶體限制:256MB

描述

80 Days is an interesting game based on Jules Verne's science fiction "Around the World in Eighty Days". In this game, you have to manage the limited money and time.

Now we simplified the game as below:

There are n cities on a circle around the world which are numbered from 1 to n by their order on the circle. When you reach the city i at the first time, you will get ai dollars (ai can even be negative), and if you want to go to the next city on the circle, you should pay bi dollars. At the beginning you have c dollars.

The goal of this game is to choose a city as start point, then go along the circle and visit all the city once, and finally return to the start point. During the trip, the money you have must be no less than zero.

Here comes a question: to complete the trip, which city will you choose to be the start city?

If there are multiple answers, please output the one with the smallest number.

輸入

The first line of the input is an integer T (T ≤ 100), the number of test cases.

For each test case, the first line contains two integers n and c (1 ≤ n ≤ 106, 0 ≤ c ≤ 109).  The second line contains n integers a1, …, an  (-109 ≤ ai ≤ 109), and the third line contains n integers b1, …, bn (0 ≤ bi ≤ 109).

It's guaranteed that the sum of n of all test cases is less than 106

輸出

For each test case, output the start city you should choose.

提示

For test case 1, both city 2 and 3 could be chosen as start point, 2 has smaller number. But if you start at city 1, you can't go anywhere.

For test case 2, start from which city seems doesn't matter, you just don't have enough money to complete a trip.

樣例輸入

2
3 0
3 4 5
5 4 3
3 100
-3 -4 -5
30 40 50

樣例輸出

2
-1

題意:n個成環的城市,到達第i個城市獲得ai  ​ ,離開丟掉bi  ​ ,初始有c,全程擁有值不能為負數,問是否可行,可行就輸出最小的出發點。

先用倍增法擴大陣列長度,考試時,想到用尺取法,一心思的想維護這段區間的最小值,當區間的最小值處,滿足,但是,接著end往後加,加到這不滿足了,說明 當前位置比前面維護的最小值更小,所以這時候就讓減去a[star],star++,就行了; 當時就是一心的想維護前面的最小值,導致最終也沒寫出來,說明思考的不透徹;

程式碼:

#include<bits/stdc++.h>
using namespace std;
#define Max 1000005
#define ll long long 
ll a[2*Max],b[Max],c;
int n;
int main()
{
	int t;
 	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%lld",&n,&c);
		for(int i= 1;i<=n;i++)
			scanf("%lld",&a[i]);
		for(int i = 1;i<=n;i++)
		{
			scanf("%lld",&b[i]);
			a[i] = a[i] - b[i];
			a[i+n] = a[i];
		}
		ll sum = c;
		for(int i = 1;i <= n;i ++)
			sum+= a[i];
		if(sum<0)
		{
			printf("-1\n");
			continue;
		}
		sum = 0;
		int star = 1,end = 1,flag = 0;
		while(end<=2*n)
		{
			if(sum+c<0)
			{
				sum -= a[star];
				star++;
				if(star>end)
					end = star;
			}
			else
			{
				sum += a[end];
				if(end-star+1 == n&& sum+c>=0)
				{
					flag = star;
					break;
				}
				end++;
			}		
		}
		if(flag) printf("%d\n",flag);
		else printf("-1\n");
	}
	return 0;
}