HNOI2009 梦幻布丁
Solution
把每一种数字想象成一个队列。如果暴力合并,时间复杂度必然很高,考虑启发式合并:每次把数字少的队列合并到数字多的队列上去。每次合并,若数字少的队列数字个数为 \(s\),则合并之后产生新队列的大小必定不小于 \(2*s\)。时间复杂度 \(O(n \log_n)\)。
这样合并产生了一个问题:即原来要求将 \(a\) 全部变为 \(b\),现在将 \(b\) 全部变为了 \(a\)。需要标记一下每种数字本来是多少,若合并时出现问题,将 \(a\)、\(b\) 的标记值互换。
Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const int N = 2333333;
int n, m, ans = 0, opt, x, y, a[N], f[N], sz[N], st[N], head[N], nxt[N];
void solve(int x, int y)
{
for(int i = head[x]; i; i = nxt[i])
{
if(a[i - 1] == y) ans--;
if(a[i + 1] == y) ans--;
}
for(int i = head[x]; i; i = nxt[i]) a[i] = y;
nxt[st[x]] = head[y], head[y] = head[x], sz[y] += sz[x];
head[x] = st[x] = sz[x] = 0;
}
int main()
{
scanf("%d%d", &n, &m);
memset(sz, 0, sizeof(sz));
memset(head, 0, sizeof(head));
for(int i = 1; i <= n; i++)
{
scanf("%d", &a[i]), f[a[i]] = a[i];
if(a[i] != a[i - 1]) ans++;
if(!head[a[i]]) st[a[i]] = i;
sz[a[i]]++, nxt[i] = head[a[i]], head[a[i]] = i;
}
for(int i = 1; i <= m; i++)
{
scanf("%d", &opt);
if(opt == 1)
{
scanf("%d%d", &x, &y);
if(x == y) continue;
if(sz[f[x]] > sz[f[y]]) swap(f[x], f[y]);
if(sz[f[x]] == 0) continue;
solve(f[x], f[y]);
}
else printf("%d\n", ans);
}
return 0;
}