1. 程式人生 > >ZOJ - 3981 Balloon Robot——思維

ZOJ - 3981 Balloon Robot——思維

先選1作為起始點跑一遍不高興值,按不高興值從小到大排序,然後順序掃描,當要把第i個位置變為0時,實際上就是將i前面的元素+m,然後整體-unhappy[i]

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
typedef long long ll;
int t, n, q;
ll m, s[maxn], a[maxn], b[maxn];
ll unhappy[maxn];
int main() {
    scanf("%d", &t);
    while (t--) {
        scanf("%d%lld%d", &n, &m, &q);
        for (int i = 1; i <= n; i++) scanf("%lld", &s[i]);
        for (int i = 1; i <= q; i++) scanf("%lld%lld", &a[i], &b[i]);
        for (int i = 1; i <= q; i++) {
            ll x = (s[a[i]]-2+m)%m+1;
            if (x >= b[i]) {
                unhappy[i] = x - b[i];
            }
            else {
                ll k = ceil((1.0*b[i]-x)/m);
                unhappy[i] = k*m+ x - b[i];
            }
        }
        sort(unhappy+1, unhappy+1+q);
        ll sum = 0;
        for (int i = 1; i <= q; i++) sum += unhappy[i];
        ll ans = sum;
        for (int i = 1; i <= q; i++) {
            ans = min(ans, sum+(i-1)*m-q*unhappy[i]);
        }
        printf("%lld\n", ans);
    }
    return 0;
}