题目:
思路在注释中
#include<bits/stdc++.h>
#define endl '\n'
#define int long long
#define buug() std::cerr<<"\t---------debug---------\n"
#define bug(n) std::cerr<<#n<<": "<<n<<endl
using namespace std;
using ULL=unsigned long long;
//using LL=long long;
using PII=pair<int,int>;
void debug() {std::cerr << "\n";}
template<class T, class... Args>
void debug(T v, Args... args) {
std::cerr <<v<< " ";
debug(args...);
}
const int N=6e5+10,MX=0x3f3f3f3f;
int n,t,m,k;
int ar[N];
int nu[N];
int st[N];
signed main(){
ios::sync_with_stdio(false);cin.tie(0);
//fstream cin; cin.open("in.txt",ios::in);
cin>>t;
while(t--){
cin>>n>>m;
for(int i=1;i<=n+m;++i){
nu[i]=0;//存数字i在这m+1个数组中出现了几次(每个数组最多出现一次,这是题目已知的);
st[i]=0;//记录i这个位置连续多少次没有改变,一直是同一个数字;(一共有m+1个数组,比较相邻俩个数组中下标i上面的数字是否一样
}
for(int i=1;i<=n;++i){
cin>>ar[i];
}
for(int i=1;i<=m;++i){
int p,v;
cin>>p>>v;
if(ar[p]!=v){
nu[ar[p]]+=i-st[p];//i - st[p]上个数的出现的次数,st[p]是上一次数出现的位置
st[p]=i;
ar[p]=v;
}
}
for(int i=1;i<=n;++i){
nu[ar[i]]+=m-st[i]+1;//最终更新到最后是没有更新过,也没有记录的,所以要记录上
}
/*
在总共m+1个数组中,假设a这个数字在数组中出现了p次
那么这m+1个数组可以分为:S1.有a这个数字p个,S2.没有a这个数字m+1-p个
那么这个数字对整个全局的贡献就是:S1:C(p,2)排列组合
S2:p*(m+1-p);
S1+S2即为数字a 的贡献
*/
int res=0;
for(int i=1;i<=n+m;++i){
res+=nu[i]*(m+1-nu[i]);
res+=nu[i]*(nu[i]-1)/2;
}
cout<<res<<endl;
}
return 0;
}