注意题目中意思是要让x颜色的集合合并到y集合中,这样并不满足启发式合并;
但是我们可以转换一下,开一个颜色的映射,具体自己可以模拟一下:
[1 2 2 2 1 3 3]
x=2 , y=1
代码
#include<iostream>
#include<queue>
#include<cstring>
#include<vector>
#include<stdio.h>
#include<map>
#include<algorithm>
#include<deque>
#include<stack>
#include<set>
// #include <unordered_map>
#include<math.h>
#include<string.h>
#define IOS ios::sync_with_stdio(false),cin.tie(0);
using namespace std;
#define pb push_back
#define coutl cout<<"------------"<<endl;
#define fi first
#define se second
#define ire(x) scanf("%d",&x)
#define iire(a,b) scanf("%d %d",&a,&b)
#define lre(x) scanf("%lld",&x)
#define llre(a,b) scanf("%lld %lld",&a,&b)
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define endl "\n"
#define PI acos(-1.0)
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef pair<double, int> PDI;
typedef pair<ll, ll> PLL;
typedef pair<double, double> PDD;
typedef pair<double, pair<int, double> > PDID;
typedef pair<char, char> PCC;
typedef pair<char, pair<int, int> > PCII;
typedef pair<int, pair<int, int> > PIII;
typedef pair<int, pair<int, pair<int, int> > > PIIII;
typedef pair<ll, pair<int, int> > PLII;
const int maxn = 1e6 + 7;
const int N = 1e6 + 7;
const int M = 1e6 + 7;
const int mod = 998244353;
const int inf = 0x3f3f3f3f;
// const ll INF = 0x3f3f3f3f3f3f3f3f;
const double pi = acos(-1);
const double eps = 1e-8;
ll gcd(ll a,ll b) {return b==0 ? a : gcd(b,a%b);}
ll lcm(ll a,ll b) {return a*b / gcd(a,b);}
ll qmi(ll a,ll b,ll p) {ll ans = 1; while(b) { if(b & 1) ans = ans * a % p; a = a * a % p; b >>= 1; } return ans;}
int lowbit(int x) {return x & (-x);}
int col[maxn];
int mp[maxn]; //颜色的映射
int ans = 0; //段数
vector<int> v[maxn]; //每种颜色的下标
int n,m;
void _merge(int x,int y)
{
for(auto xx : v[x])
{
if(col[xx - 1] == y) ans --;
if(col[xx + 1] == y) ans --;
}
for(auto xx : v[x])
{
col[xx] = y;
v[y].push_back(xx);
}
v[x].clear(); //记得清空
}
void solve()
{
iire(n,m);
for(int i=1;i<=n;i++)
{
ire(col[i]);
if(col[i] != col[i-1]) ans++;
mp[col[i]] = col[i];
v[col[i]].push_back(i);
}
while(m--)
{
int op;
ire(op);
if(op == 2) cout<<ans<<'\n';
else
{
int x,y;
iire(x,y);
if(x == y) continue;
if(v[mp[x]].size() > v[mp[y]].size()) swap(mp[x],mp[y]);
_merge(mp[x],mp[y]); //启发式合并(小集合合并到大集合里面)
}
}
}
int main()
{
int t;
// cin>>t;
t = 1;
while(t--)
{
solve();
}
return 0;
}