unique(起点, 终点)
和所有STL一样,左闭右开,(包括起点,不包括终点)
unique 只会去掉连续相同的数字
比如 对 1, 1, 2, 2, 1, 1, 2, 2
unique 结果是 1, 2, 1, 2
返回值是指向去重之后,最后一个元素之后的位置
所以常见用法是
m = unique(a, a + n) - a;
把 a[0], a[1], ..., a[n-1]
去重
去重之后有 m 个不同的数字
并且存在 a[0], a[1], ..., a[m-1]
位置上
a[m], a[m+1], ..., a[n-1]
应该不会变
但是你的程序不要利用这个性质
unique 只会去掉连续相同的数字
如果想不连续相同的也去掉,一般先 sort,让相同的是连续一段
去重也可以用 set
#include <bits/stdc++.h> using namespace std; int a[] = {1, 1, 2, 2, 1, 1, 2, 2}; // 1 2 1 2 // ^ return pointer // unique(...) - a = 4 int main() { int n = 8; // sort(a, a + n); for (int i = 0; i < 8; i++) { cout << a[i] << " "; } cout << endl; n = unique(a, a + n) - a; for (int i = 0; i < 8; i++) { cout << a[i] << " "; } cout << endl; cout << n << endl; return 0; }
https://atcoder.jp/contests/abc164/tasks/abc164_c
输入n个字符串问有多少个不同的字符串
#include <bits/stdc++.h> using namespace std; set<string> t; string s; int n; int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> s; t.insert(s); } cout << t.size() << endl; return 0; }
https://atcoder.jp/contests/abc240/tasks/abc240_b
输入n个数字
问有多少个不同的数字
#include <bits/stdc++.h> using namespace std; int n; int a[100020]; int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a, a + n); n = unique(a, a + n) - a; cout << n << endl; return 0; }
https://codeforces.com/problemset/problem/344/A
https://www.luogu.com.cn/problem/CF344A
输入n个字符串,去掉相邻相同的,问结果剩下几个字符串
#include <bits/stdc++.h> using namespace std; int n, a[100020]; int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } n = unique(a, a + n) - a; for (int i = 0; i < n; i++) { cout << a[i] << endl; } cout << n << endl; return 0; } // 1 1 1 2 2 2 1 1 1 // 1 2 1 // ^ ^ // a unique
https://atcoder.jp/contests/abc143/tasks/abc143_c
输入n个字符,去掉相邻相同的,问结果剩下几个字符
#include <bits/stdc++.h> using namespace std; int n; char s[100020]; int main() { cin >> n >> s; cout << unique(s, s + n) - s << endl; return 0; }
https://atcoder.jp/contests/abc164/tasks/abc164_c
输入n个字符串问有多少个不同的字符串
#include <bits/stdc++.h> using namespace std; set<string> t; string s; int n; int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> s; t.insert(s); } cout << t.size() << endl; return 0; }