#C7287. Gas Station Circuit

    ID: 51141 Type: Default 1000ms 256MiB

Gas Station Circuit

Gas Station Circuit

You are given two integer arrays gas and cost of length n where gas[i] represents the amount of gas at the ith gas station and cost[i] represents the cost of gas required to travel from the ith station to the (i+1)th station. The route forms a circular circuit. Your task is to determine if there exists a starting gas station from which you can travel around the circuit once without running out of gas. If such a station exists, output its index; otherwise, output \(-1\).

The problem can be mathematically formulated as follows:

Let \(\text{total} = \sum_{i=0}^{n-1}(\text{gas}_i - \text{cost}_i)\). If \(\text{total} < 0\), then it is impossible to complete the circuit. Otherwise, there exists an index \(s\) (the starting gas station) such that starting from \(s\) the accumulated gas is non-negative throughout the journey.

Note: The index of the gas station starts from 0.

inputFormat

The input is read from stdin and has the following format:

n
 gas[0] gas[1] ... gas[n-1]
 cost[0] cost[1] ... cost[n-1]

Where:

  • n is the number of gas stations.
  • The next line contains n integers representing the gas available at each station.
  • The following line contains n integers representing the cost to travel from each station to the next one.

outputFormat

Print a single integer to stdout: the starting gas station's index if the circuit can be completed, or -1 if it cannot.

## sample
5
1 2 3 4 5
3 4 5 1 2
3

</p>