P12006 【MX-X10-T2】[LSOT-4] 网易云 题解

· · 题解

P12006 【MX-X10-T2】[LSOT-4] 网易云 题解

题目传送门

题意

一共有 n 首歌,每首歌都有一个好听值 x_i,给你一个长度为 n - 1 的序列 s,s_i = x_i + x_{i + 1}。

再给你 m 对数 a_i, b_i,表示第 a_i 首歌听了 b_i 次,求 \sum_{i=1}^{m} x_{a_i} \times b_i。

分析

我们先开一个 cnt 数组,cnt_i 表示第 i 首歌听了几次。

然后我们从 1 开始往 n 遍历,对于每一个 i,由于我们一定要听够 cnt_i 遍这首歌,然后我们知道 i 和 i + 1 的好听值总和,所以我们可以把答案增加 s_i \times cnt_i,然后将 cnt_{i + 1} 减掉这次已经听过的次数,即减掉 cnt_i。

这时候 cnt_{i + 1} 可能变成负数,但是可以不用理它,有因为可以在后面听歌次数为正数的时候补回来。

至于怎么判断无解,我们只需要看遍历完了以后 cnt_n 是不是等于 0 就可以了,如果不等于 0,说明前面有补不回来的次数,也就是说无解。

代码

#include <algorithm>
#include <iostream>
#include <cstdio>
#define LL long long
//#define int long long

using namespace std;

const int N = 1e5 + 10;

int n, m;
int s[N];
int cnt[N];
LL ans;

int main() {
    scanf("%d%d", &n, &m);
    for (int i = 1; i < n; i ++ )
        scanf("%d", s + i);
    for (int i = 1; i <= m; i ++ ) {
        int a, b;
        scanf("%d%d", &a, &b);
        cnt[a] += b;
    }
    for (int i = 1; i <= n; i ++ ) {
        cnt[i + 1] -= cnt[i];
        ans += cnt[i] * s[i];
    }
    if (cnt[n] != 0)
        printf("Impossible\n");
    else
        printf("%lld\n", ans);
    return 0;
}