time limit per test 2 seconds
memory limit per test 256 megabytes
input standard input
output standard output
You are beta testing the new secret Terraria update. This update will add quests to the game!
Simply, the world map can be represented as an array of length nn, where the i-th column of the world has height ai.
There are mm quests you have to test. The j-th of them is represented by two integers sjsj and tjtj. In this quest, you have to go from the column sjsj to the column tj. At the start of the quest, you are appearing at the column sjsj.
In one move, you can go from the column xx to the column x−1 or to the column x+1. In this version, you have Spectre Boots, which allow you to fly. Since it is a beta version, they are bugged, so they only allow you to fly when you are going up and have infinite fly duration. When you are moving from the column with the height p to the column with the height q, then you get some amount of fall damage. If the height p is greater than the height q, you get p−q fall damage, otherwise you fly up and get 0 damage.
For each of the given quests, determine the minimum amount of fall damage you can get during this quest.
Input
The first line of the input contains two integers nn and mm (2≤n≤10^5;1≤m≤10^5) — the number of columns in the world and the number of quests you have to test, respectively.
The second line of the input contains nn integers a1,a2,…,an (1≤ai≤109), where aiai is the height of the ii-th column of the world.
The next mm lines describe quests. The jj-th of them contains two integers sj and tj (1≤sj,tj≤n;sj≠tj), which means you have to move from the column sj to the column tj during the j-th quest.
Note that sj can be greater than tj.
Output
Print mm integers. The j-th of them should be the minimum amount of fall damage you can get during the j-th quest completion.
Example
input
Copy
7 6
10 8 9 6 8 12 7
1 2
1 7
4 6
7 1
3 5
4 2
output
Copy
2
10
0
7
3
1
题目意思很好理解,我们需要的是用个dp[k]表示从1到k(k>=1&&k<=n)之间的距离,然后输出就行了。
#include <iostream>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
int data1[100002];
long long dp1[100002];
long long dp2[100002];
for (int i = 1; i <= n; i++)
{
cin >> data1[i];
}
data1[0]=data1[n+1]=0;
for(int i=1;i<=n;i++)
{
if(data1[i-1]>data1[i])
{
dp1[i]=data1[i-1]-data1[i]; /*dp[i]现在表示从i-1到i的距离*/
}
else
{
dp1[i]=0;
}
}
for(int i=n;i>=1;i--)
{
if(data1[i+1]>data1[i])
{
dp2[i]=data1[i+1]-data1[i];
}
else
{
dp2[i]=0;
}
}
for(int i=1;i<=n;i++)
{
dp1[i]=dp1[i]+dp1[i-1];
}
for(int i=n;i>=1;i--)
{
dp2[i]=dp2[i+1]+dp2[i];
}
while (m >0)
{
int sj = 0, tj = 0;
cin >> sj >> tj;
if (sj < tj)
{
cout<<dp1[tj]-dp1[sj]<<endl;
}
else
{
cout<<dp2[tj]-dp2[sj]<<endl;
}
m--;
}
return 0;
}