【gdoi2018 day1】密码锁

题目大意:

众人皆知。

题解:

看到区间问题应该要想到差分。

于是这题就变成了水题。

差分后,排个序,随便贪一波就行了。

Code:

#include
#include
#define ll long long
#define fo(i, x, y) for(int i = x; i <= y; i ++)
using namespace std;

const int N = 1e6 + 5;

int n, m, a[N]; ll ans;

int main() {
    freopen("lock.in", "r", stdin);
    freopen("lock.out", "w", stdout);
    scanf("%d %d", &n, &m);
    fo(i, 1, n) scanf("%d", &a[i]);
    for(int i = n + 1; i; i --) a[i] = (a[i] - a[i - 1] + m) % m;
    sort(a + 1, a + n + 2);
    int r = n + 1;
    fo(i, 1, n + 1) {
        while(r > i && m - a[r] < a[i])
            ans += m - a[r], a[i] -= m - a[r], r --;
        if(i == r) break;
        a[r] += a[i]; ans += a[i];
    }
    printf("%lld", ans);
}

你可能感兴趣的:(信息学,idea题,贪心)