CodeForces - 1325B CopyCopyCopyCopyCopy (排序+unique去重)

CodeForces - 1325B CopyCopyCopyCopyCopy

在這裏插入圖片描述

題目分析:
這個題就是找 不重複的元素有多少個,排序+去重就好了,這裏主要想學一個STL 的去重函數

AC代碼

#include<stdio.h>
#include<cmath>
#include<iostream>
#include<string.h>
#include<cstring>
#include<string>
#include<stdlib.h>
#include <algorithm>
#define LL long long
#define rep(i , j , n) for(int i = j ; i <= n ; i++)
#define red(i , n , j)  for(int i = n ; i >= j ; i--)
using namespace std;
const int maxn = 1e6;
const double PI = acos(-1.0);
int T;
int n,a[maxn];  
int main(){
    scanf("%d",&T);
    while(T--){
    	LL ans=0;
        scanf("%d",&n);
        rep(i,1,n)
        scanf("%d",&a[i]);
        sort(a+1,a+1+n);
        a[n+1]=-100000;//爲了確保正確,處理一下邊界。
        rep(i,1,n)
        if(a[i]!=a[i+1])//相鄰兩個不一樣,就記一次
        ans++;
        printf("%lld\n",ans);

    }
    return 0;
}

上面這是我寫的代碼,在再看大佬的去重:

在這裏插入圖片描述這裏用的是 unique()去重函數

unique()是C++標準庫函數(#include < algorithm>)裏面的函數,其功能是去除相鄰的重複元素(只保留一個),所以使用前需要對數組進行排序
n = unique(a,a+n) - a 返回的是去重後的數組長度,如果你用的是從1 開始的數組,那麼,就像大佬寫的那樣m=unique(a+1,a+1+n)-(a+1);
更具體的方法請看大佬的博客

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章