C. Serval and Toxel's Arrays
链接:https://www.luogu.com.cn/problem/CF1789C or https://codeforces.com/problemset/problem/1789/C
题目:
大佬思路:
有点像链式前向星的思路,就是通过记录前一个的位置来记录连续存储长度。
代码:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<string>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<map>
#include<queue>
#include<limits.h>
#include<climits>
#include<fstream>
#include<stack>
#define IOS ios::sync_with_stdio(false), cin.tie(0) ,cout.tie(0)
using namespace std;
typedef long long ll;
const int N = 2e5 + 10;
int lst[N*2], sum[N*2],a[N];
int n, m;
int main()
{
IOS;
int t; cin >> t;
while (t--)
{
cin >> n >> m;
memset(lst, -1, sizeof(lst)), memset(sum, 0, sizeof(sum));
int maxn = 0;
for (int i = 0; i < n; i++) { int x; cin >> x; lst[x] = 0; a[i + 1] = x; maxn = max(maxn, x); }
for (int i = 1; i <= m; i++)
{
int ax, bx;
cin >> ax >> bx;maxn = max(maxn, bx);
sum[a[ax]] += i - lst[a[ax]];
lst[a[ax]] = -1;
a[ax] = bx;
lst[bx] = i;
}
ll ans = 0;
for (int i = 1; i <= n; i++)
if (lst[a[i]] !=-1)
sum[a[i]] += m + 1 - lst[a[i]];
for (int i = 1; i <= maxn; i++)
{
ll x = sum[i];
ans += x * (x - 1) / 2 + x * (m + 1 - x);
}
cout << ans << '\n';
}
return 0;
}
注意要开unsigned long long防越界