A through 1600: (Example 4) travel problems

Title Description

John intends to drive a car to travel around a ring road.
A total of n stations on the road, every station has a number of liters of gasoline (fuel and some stations may be zero), per liter of oil can make cars with one thousand meters.
John must proceed from a station, has been in a clockwise (or counterclockwise) direction traveled all the stations and back to the starting point.
In the beginning of time, car fuel is zero, John each station, the station put all the oil are put on (starting point is also true), the process of moving without oil situation can not occur.
Task: to determine whether each station as a starting point for success by traveling the week.

SAMPLE INPUT

5
3 1
1 2
5 2
0 1
5 4

Sample Output

TAK
NIE
TAK
NIE
TAK

Algorithm 1

(Violence analog) \ (O (^ n-2) \)

Can not afford...

C ++ code

不会QAQ

Algorithm 2

(Heap optimization) \ (O (nlogn) \)

And in fact a bit like a positive solution:
We might as well merge into an a array, so that a [i] = p [i ] -d [i], indicate increases and decreases the amount of oil.
We can maintain a pre prefix and to store, then we go on the road can be determined by the difference, we have to determine whether to go one way to succeed, then they would have to see whether this road oil minimum conditions greater than zero.
We can use the stack to store.
But still super.

C ++ code

不会QAQ

Correct

(Monotone queue optimization)

The split ring to form a chain running.
Reverse run twice, if the prefix and road maintenance, content is the contribution of each gas station, which is pd. If there is a prefix on the road and less than 0, then it does not work this way , positive and negative run twice on the line.

c ++ Code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e6+5;
const int INF=0x3f3f3f3f;
int n;
ll s[N<<1];
bool ans[N];
int head,tail;
int p[N],d[N],a[N<<1],q[N];
int main() {
    scanf("%d",&n);
    for(int i=1; i<=n; i++) scanf("%d%d",&p[i],&d[i]);
    d[0]=d[n];
    for(int i=1; i<=n; i++) a[i]=a[n+i]=p[i]-d[i];
    for(int i=1; i<n<<1; i++) s[i]=s[i-1]+a[i];
    head=1,tail=0;
    for(int i=1; i<n<<1; i++) {
        while(head<=tail&&i-n>=q[head]) ++head;
        while(head<=tail&&s[q[tail]]>=s[i]) --tail;
        q[++tail]=i;
        if(i>=n&&s[q[head]]>=s[i-n]) ans[i-n+1]=1;
    }
    for(int i=1; i<=n; i++) a[i]=a[i+n]=p[n-i+1]-d[n-i];
    for(int i=1; i<n<<1; i++) s[i]=s[i-1]+a[i];
    head=1,tail=0;
    for(int i=1; i<n<<1; i++) {
        while(head<=tail&&i-n>=q[head]) ++head;
        while(head<=tail&&s[q[tail]]>=s[i]) --tail;
        q[++tail]=i;
        if(i>=n&&s[q[head]]>=s[i-n]) ans[(n<<1)-i]=1;
    }
    for(int i=1; i<=n; i++) {
        if(ans[i]) puts("TAK");
        else puts("NIE");
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/Fast-Bird/p/11851523.html