First of all we divide our problem into 2 parts: consider stations from which we can start if we are moving in the clockwise direction and stations from which we can start if we are moving in the counterclockwise direction.
Obviously, if we know the solution of one of these problems, we know the solution of another problem.
So, we may assume that stations are located in the counterclockwise order and we are moving in the counterclockwise direction.
Consider the following differences:
D1=a1-b1,
D2=(a1+a2)-(b1+b2),
D3=(a1+a2+a3)-(b1+b2+b3),
…
Dn=(a1+a2+…+an)-(b1+b2+…+bn);
Obviously if one of Di’s is less than a zero, then we cannot drive one round along the road. Let D = min(Di) – we will use it later.
Obviously, if D<0 then the first station cannot be the start station.
Now, we can check with complexity O(n) whether the first station can be used as the starting point. Next, we want to show how we can check this for the second station with complexity O(1).
To show this, consider:
E1=D1-(a1-b1),
E2=D2-(a1-b1),
…
En=Dn-(a1-b1).
Next, substitute Di in these equalities. We get the following:
E1=(a1-b1)-(a1-b1)=0=(a2+a3+…+an+a1)-(b2+b3+…+bn+b1) – (a1+…+an=b1+…+bn=X)
E2=(a1+a2)-(b1+b2)-(a1-b1)=a2-b2
E3=(a1+a2+a3)-(b1+b2+b3)-(a1-b1)=(a2+a3)-(b2+b3)
…
En=(a1+a2+…+an)-(b1+b2+…+bn)-(a1-b1)=(a2+…+an)-(b2+…+bn)
But it’s easy to see that number E1 has the same meaning for the second station as number D1 for the first one. So, we just have to check min(Ei)>=0. But Ei=Di-(a1-b1), so we have to check min(Di-(a1-b1))>=0. Now, we can see that if min(Di)=Dk, then min(Di-(a1-b1))=Dk-(a1-b1). So, if we know Dk, that we can check whether the second station can be the starting point with complexity O(1). Similarly, we can check this for the third, the fourth, …, the nth stations.
Now we should check the same things but assuming that the car is moving in the clockwise direction.
--------------------------------------------------------------------------------------------------------------------------
#include <iostream> #include <cstdio> using namespace std; const int maxn=111111; const int OO=1e9; int gas[maxn],dis[maxn]; bool v[maxn]; int n,Dk,sum,ans; int main() { scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&gas[i]); for(int i=0;i<n;i++) scanf("%d",&dis[i]); Dk=OO; sum=0; for(int i=0;i<n;i++) { sum+=gas[i]-dis[i]; Dk=min(Dk,sum); } ans=0; for(int i=0;i<n;i++) { if(Dk>=0 && !v[i]) { v[i] = true; ans++; } Dk-=gas[i]-dis[i]; } Dk=OO; sum=0; for(int i=n-1;i>=0;i--) { sum+=gas[i]-dis[(i-1+n)%n]; Dk=min(Dk,sum); } for(int i=n-1;i>=0;i--) { if(Dk >= 0 && !v[i]) { v[i]=true; ans++; } Dk-=gas[i]-dis[(i-1+n)%n]; } printf("%d\n", ans); for(int i=0;i<n;i++) { if(v[i]) { printf("%d ", i+1); } } printf("\n"); return 0; }