#P40022. 2019 ICPC NA Qualifier Contest L - Traveling Merchant

2019 ICPC NA Qualifier Contest L - Traveling Merchant

题目描述

There is a long east-west road which has nn towns situated along it, numbered 11 to nn from west to east. All towns buy and sell the same kind of goodie. The value of a goodie fluctuates according to a weekly schedule. A town buys and sells a goodie at its value in that town on that particular day. At town ii, the value of a goodie changes by did_ i every day in the first half of a week, and changes by di-d_ i every day in the second half of a week. In other words, the value of a goodie at town ii is viv_ i on Mondays and Sundays, vi+div_ i + d_ i on Tuesdays and Saturdays, vi+2div_ i + 2d_ i on Wednesdays and Fridays, and vi+3div_ i + 3d_ i on Thursdays.

A merchant is making a business travel plan. His trip begins at a starting town ss and ends at a destination town tt, visiting each town from ss to tt (inclusive) exactly once. The merchant starts the trip on a Monday. It takes him exactly one day to travel between adjacent towns and every day he travels to the next town on the path to the destination. He may buy exactly one goodie at a town along the trip and sell that goodie at a town he visits later. He can only buy once and sell once. The merchant would like to know the maximum possible profit of qq travel plans with different choices of town ss and town tt.

输入格式

The first line of the input has a single integer nn (2n1052 \leq n \leq 10^5). The next nn lines each have two integers. The iith line has viv_ i (1vi1091 \leq v_ i \leq 10^9) and did_ i (1vi+3di1091 \leq v_ i + 3 d_ i \leq 10^9). The next line has a single integer qq (1q1051 \leq q \leq 10^5). The following qq lines each give a pair of integers ss and tt (1s,tn,st1 \leq s, t \leq n, s \neq t), representing one travel plan from town ss to town tt. If sts \le t the merchant travels west to east, otherwise he travels east to west.

输出格式

For each travel plan, output the maximum profit the merchant can make on a single line. If the merchant cannot make any profit, output 00.

样例

样例输入

5
1 2
2 1
5 0
4 -1
7 -2
5
1 5
5 1
3 1
4 5
5 4

样例输出

4
2
2
1
0