1. 程式人生 > >Codeforces Round #489 (Div. 2) ---- A. Nastya and an Array

Codeforces Round #489 (Div. 2) ---- A. Nastya and an Array

給了我們一個數組,可以給整個陣列的元素加上一個數或者減去一個數,問多少次操作之後所有的數都變成了0

因為每次操作都是針對整個陣列的,那麼不相同的數一定不可能同時變成0,因此我們只需要對陣列去重即可,然後對於已經是0 的數,我們不需要給出操作,因此如果陣列中有0,答案減去1

這裡記錄一下去重的unique函式, len = unique(a,a+n) - a 要減去a的地址,這個函式是針對相鄰的元素的,因此要求先對a陣列排序才可以去重成功

程式碼如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 10;
int a[maxn];
int main(){
    int n;
    cin >> n;
    for (int i=0; i<n; i++)
        cin >> a[i];
    sort(a, a+n);
    int len = (int) (unique(a, a+n) - a);
    int ans = len;
    for (int i=0; i<len; i++) {
        if (a[i] == 0) ans--;
    }
    cout << ans << endl;
    return 0;
}