B. Alyona and flowers
Problem Description:
Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.
For example, consider the case when the mother has 5 flowers, and their moods are equal to 1, - 2, 1, 3, - 4. Suppose the mother suggested subarrays (1, - 2), (3, - 4), (1, 3), (1, - 2, 1, 3). Then if the girl chooses the third and the fourth subarrays then:
the first flower adds 1·1 = 1 to the girl's happiness, because he is in one of chosen subarrays,
the second flower adds ( - 2)·1 = - 2, because he is in one of chosen subarrays,
the third flower adds 1·2 = 2, because he is in two of chosen subarrays,
the fourth flower adds 3·2 = 6, because he is in two of chosen subarrays,
the fifth flower adds ( - 4)·0 = 0, because he is in no chosen subarrays.
Thus, in total 1 + ( - 2) + 2 + 6 + 0 = 7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!
Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
Input:
The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of flowers and the number of subarrays suggested by the mother.
The second line contains the flowers moods — n integers a1, a2, ..., an ( - 100 ≤ ai ≤ 100).
The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1 ≤ li ≤ ri ≤ n) denoting the subarray a[li], a[li + 1], ..., a[ri].
Each subarray can encounter more than once.
Output:
Print single integer — the maximum possible value added to the Alyona's happiness.
Sample Input:
5 4
1 -2 1 3 -4
1 2
4 5
3 4
1 4
Sample Output:
7
【题目链接】B. Alyona and flowers
【题目类型】
&题意:
给m个区间,你要选几个使得区间内的元素乘区间选择的次数最大,问这个最大值是多少?
&题解:
模拟遍样例,再加仔细想想,发现只有这个区间所有数加起来>0的时候才要选,并且对答案的贡献也就是>0的这个数,所有把符合区间的这个数相加就好了。
【时间复杂度】O(\(n^2\))
&代码:
#include <bits/stdc++.h>
#define SI(N) scanf("%d",&(N))
#define SII(N,M) scanf("%d %d",&(N),&(M))
#define rez(i,a,b) for(int i=(a);i<=(b);i++)
const int maxn = 100 + 9 ;
int n, m, a[maxn], u, v, res;
int main() {
while (~SII(n, m)) {
res = 0;
rez(i, 1, n) SI(a[i]);
rez(i, 1, m) {
SII(u, v);
int ans = 0;
rez(j, u, v) {
ans += a[j];
}
res += ans > 0 ? ans : 0;
}
printf("%d\n", res);
}
return 0;
}