把n个x共同相对x以外的数减一需要n步,相对减k则需要k*n步,因此一个公式for循环就跑出来了。
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <bits/stdc++.h>
using namespace std;
int A[100009];
int main(){
int N;
cin>>N;
for(int i=0;i<N;i++){
scanf("%d",&A[i]);
}
sort(A,A+N);
long long ans=0;
int i=0;
while(i<N){
while(i<=N-2&&A[i+1]==A[i])++i;
if(i==N-1)break;
ans+=(A[i+1]-A[i])*(N-1-i);
++i;
}
cout<<ans<<endl;
return 0;
}
//
// _oo0oo_
// o8888888o
// 88" . "88
// (| -_- |)
// 0\ = /0
// ___/`---'\___
// .' \\| |// '.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' |_/ |
// \ .-\__ '-' ___/-. /
// ___'. .' /--.--\ `. .'___
// ."" '< `.___\_<|>_/___.' >' "".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `_. \_ __\ /__ _/ .-` / /
// =====`-.____`.___ \_____/___.-`___.-'=====
// `=---='
//
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// 佛祖保佑 永无BUG
//
//
//