[JZOJ 5698] 密码锁

思路:
差分+排序

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 1000010;
int n,m;
int a[maxn];
ll ans;
int main () {
	freopen("lock.in","r",stdin);
	freopen("lock.out","w",stdout);
	scanf("%d %d",&n,&m);
	for(int i = 1;i <= n; ++i) {
		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;
	for(int i = 1;i <= n + 1; ++i) {
		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\n",ans);
	return 0;
} 
/*
Sample Input1
4 3
1 2 1 0

Sample Input2
11 8 
1 2 3 4 5 0 5 4 3 2 1

Sample Input3
20 100
30 91 15 72 61 41 10 37 98 41 94 80 26 96 10 88 59 5 84 14
 
 Sample Output1
2

Sample Output2
8

Sample Output3
313
*/
原文地址:https://www.cnblogs.com/akoasm/p/9562638.html