http://hihocoder.com/problemset/problem/1831
时间限制: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 ≤ 10^6, 0 ≤ c ≤ 10^9). The second line contains n integers a1, …, an (-10^9 ≤ ai ≤ 10^9), and the third line contains n integers b1, …, bn (0 ≤ bi ≤ 10^9).
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
比赛时的做法:对于选取的第i个起点,用线段树查询区间[i,n]的最大前缀和代价以及[i,n]代价之和,如果满足条件,则money - 代价和,再区间[1,i]的最大前缀和代价以及[1,i]代价之和,结果TLE了....算了算这样做的时间代价是O(nlogn)果断超时啊...
网络赛结束之后上网搜索了一下别人的解法:先将a b [1,n]序列扩充成a b[1,2n]序列,其中a[i] = a[i +n],b[i] = b[i + n](i <=n),再用队列暂时满足的点,如果不满足则弹出,直到队列中的元素>=n ,然后就AC了,代码如下
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
int a[maxn * 2],b[maxn * 2];
int main()
{
int t , n;
long long money;
cin>>t;
while(t--)
{
bool flag = false;
queue<long long>q;
cin>>n>>money;
for(int i = 1;i <= n;i++)
cin>>a[i];
for(int i = 1;i <= n;i++)
cin>>b[i];
for(int i = n + 1;i<= 2 * n;i++)
{
a[i] = a[i - n];
b[i] = b[i - n];
}
for(int i = 1;i <= 2 * n;i++ )
{
if(money + a[i] -b[i] >=0 )
{
money += a[i] -b[i];
q.push(i);
if(q.size() >=n)
{
cout<<q.front()<<endl;
flag = true;
break;
}
continue;
}
while(money + a[i] -b[i] <0 && !q.empty())//try to start at next city
{
money -=a[q.front()] -b[q.front()]; //give back the cost money
q.pop();
}
if(money + a[i] -b[i] >= 0)i--;//caculate at the next time
}
if(flag == false)cout<<-1<<endl;
}
}
还是太菜了QAQQQ