题解:CF2126F 1-1-1, Free Tree!
翻译:
给定一个
定义第
如果这条边连接的节点颜色相同(即
有
正难则反。我们预处理出所有
考虑根号分治。设置阈值为
我们可以用个数组
在查询时,对于度较少的点,直接暴力统计;而对于度较多的点,直接在
显然度较多的点不会超过
大功告成……了吗?
交上去会发现直接 MLE 了,原来数组大小约为
注意到本题时间限制较为宽松,故考虑调整
代码如下:
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/hash_policy.hpp>
#include <algorithm>
#include <iostream>
#include <random>
#include <cstdio>
#include <vector>
#include <cmath>
#include <ctime>
#define int long long
using namespace __gnu_pbds;
using namespace std;
mt19937 rng;
unsigned s1, s2, s3;
int a[200005];
int sizes[200005];
vector <pair <int, int>> v[200005];
int siz;
vector <int> big;//记录度较多的点
int idx[200005];
vector <pair <int, int>> v2[200005];
int cont[105][200005];//建立一个数组直接统计
void solve(){
int n, m;
cin >> n >> m;
for(int i = 1; i <= n; i++) cin >> a[i];
int ans = 0;
for(int i = 1; i < n; i++){
int x, y, z;
cin >> x >> y >> z;
v[x].push_back({y, z});
v[y].push_back({x, z});
sizes[x]++, sizes[y]++;
if(a[x] != a[y]) ans += z;//预处理出所有 C_i 的和
}
nth_element(sizes + 1, sizes + min(100ll, n) + 1, sizes + n + 1, greater <int>());
siz = sizes[min(100ll, n)] + 1;
for(int i = 1; i <= n; i++){
if(v[i].size() >= siz){//记录度较多的点
big.push_back(i), idx[i] = big.size() - 1;
}
}
for(int i = 1; i <= n; i++){
for(auto j:v[i]){
if(v[j.first].size() >= siz){
v2[i].push_back(j);
cont[idx[j.first]][a[i]] += j.second;//预处理出贡献
}
}
}
while(m--){
int x, y;
cin >> x >> y;
if(v[x].size() < siz){//度较少的点直接暴力计算
for(auto i:v[x]){
if(a[i.first] != a[x]) ans -= i.second;
if(a[i.first] != y) ans += i.second;
}
}else{
ans += cont[idx[x]][a[x]];//直接查表
ans -= cont[idx[x]][y];
}
for(auto i:v2[x]){
cont[idx[i.first]][a[x]] -= i.second;//更新数组
cont[idx[i.first]][y] += i.second;
}
a[x] = y;
cout << ans << '\n';
}
for(int i = 1; i <= n; i++){//记得清空
v[i].clear();
v2[i].clear();
idx[i] = 0;
}
for(int i = 1; i <= 100; i++){
for(int j = 1; j <= n; j++){
cont[i][j] = 0;
}
}
big.clear();
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
rng.seed(time(0));
s1 = rng(), s2 = rng(), s3 = rng();
int t;
cin >> t;
while(t--) solve();
return 0;
}
通过记录