题意:n只袜子,穿m天,每只袜子有一种颜色,有k种颜料对袜子染色,接下来的m天每天给你指定两只袜子穿,问现在最少需要染色多少次才能使得接下来的m天每天穿的袜子颜色都相同。注意是一次性染色。
题解:并查集
既然是一次性染色,那么就对所在同一集合的袜子染相同颜色,我们不关心袜子出现几次,所以染的颜色取决于集合中颜色最多的是哪个。
用vector存以根为代表的集合含有的颜色,map存个数,遍历求最多即可。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
const int Max = 2e5 + 5;
int Parent[Max], Rank[Max], rep[Max], cnt;
int Find(int x) {
return Parent[x] == x ? x : Parent[x] = Find(Parent[x]);
}
void Union(int x, int y) {
int u, v, root;
u = Find(x);
v = Find(y);
if (u == v) {
return;
}
if (Rank[u] <= Rank[v]) {
rep[v] += rep[u];
root = Parent[u] = v;
if (Rank[u] == Rank[v])
Rank[v]++;
}
else {
rep[u] += rep[v];
root = Parent[v] = u;
}
//return root;
}
int n, m, k, l, r, c[Max];
vector<int> v[Max];
map<int, int> co;
bool cmp(int x, int y) {
return x > y;
}
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= n; i++) scanf("%d", &c[i]);
for (int i = 1; i <= n; i++) Parent[i] = i, rep[i] = 1;
for (int i = 1; i <= m; i++) {
scanf("%d%d", &l, &r);
Union(l, r);
}
for (int i = 1; i <= n; i++) {
if (rep[Find(i)] == 1) continue;
v[Find(i)].push_back(c[i]);
}
int num = 0;
for (int i = 1; i < Max - 1; i++) {
int siz = v[i].size();
if (siz) {
co.clear();
int ma = 0;
for (int j = 0; j < siz; j++) {
co[v[i][j]]++;
ma = max(ma, co[v[i][j]]);
}
num += siz - ma;
}
}
printf("%d\n", num);
return 0;
}