【codeforces 546B】Soldier and Badges

time limit per test3 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it’s owner reached. Coolness factor can be increased by one for the cost of one coin.

For every pair of soldiers one of them should get a badge with strictly higher factor than the second one. Exact values of their factors aren’t important, they just need to have distinct factors.

Colonel knows, which soldier is supposed to get which badge initially, but there is a problem. Some of badges may have the same factor of coolness. Help him and calculate how much money has to be paid for making all badges have different factors of coolness.

Input
First line of input consists of one integer n (1 ≤ n ≤ 3000).

Next line consists of n integers ai (1 ≤ ai ≤ n), which stand for coolness factor of each badge.

Output
Output single integer — minimum amount of coins the colonel has to pay.

Examples
input
4
1 3 1 4
output
1
input
5
1 2 3 2 5
output
2
Note
In first sample test we can increase factor of first badge by 1.

In second sample test we can increase factors of the second and the third badge by 1.

【题目链接】:http://codeforces.com/contest/546/problem/B

【题解】

把数字从小到大排序下;
如果有相同的数字,就整体往后移动,每个数字都往后移,直到每个数字都不一样为止;(一格一格地移动);
如果一开始这个数字就被人占据了,则所有的想同数字(len个)都同时往后移动;然后再一个一个往后移动;
移动谁都一样吧.
比较明显的贪心吧.

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define rei(x) scanf("%d",&x)
#define rel(x) scanf("%I64d",&x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int MAXN = 3e3+100;
const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);

int n;
int a[MAXN];
bool bo[MAXN*4];

int main()
{
    //freopen("F:\rush.txt","r",stdin);
    rei(n);
    rep1(i,1,n)
        rei(a[i]);
    sort(a+1,a+1+n);
    LL ans = 0;
    rep1(i,1,n)
    {
        int j = i;
        while (j+1<=n && a[j+1]==a[i])
            j++;
        int len = j-i+1;
        int idx = a[i];
        while (bo[idx])
        {
            idx++;
            ans += len;
        }
        bo[idx] = true;
        rep1(k,idx+1,idx+len-1)
        {
            bo[k] = true;
            ans+=k-idx;
        }
        i = j;
    }
    cout << ans << endl;
    return 0;
}

更牛逼的代码。

#include <iostream>
using namespace std;

bool v[10000000];

int main() {
    int r = 0, n, c;
    cin >> n;
    while (n--) {
        cin >> c;
        while (v[c]) {
            c++;
            r++;
        }
        v[c] = 1;
    }
    cout << r;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626762.html