萌新刚学 oi,TLE 求调
查看原帖
萌新刚学 oi,TLE 求调
974277
水星湖psgqwq楼主2025/7/19 12:04
#include <bits/stdc++.h>
using namespace std;

namespace z {

#define int long long
const int N = 2e5 + 5, B = 630;
int n, q, d[N], a[N];
vector<pair<int, int>> p[N], g[N];
#define ull unsigned long long
const int LEN = (1 << 23);
mt19937_64 rnd(chrono::steady_clock::now().time_since_epoch().count());

struct HashMap {
	inline ull F(ull x) {
		static const ull s1 = rnd(), s2 = rnd(), s3 = rnd();
		x += s1;
		x = (x ^ (x >> 33)) * s2;
		x = (x ^ (x >> 30)) * s3;
		return x;
	}
	ull key[LEN + 5], value[LEN + 5];
	int ver[LEN + 5], cur_ver = 1;

	inline int gt(const ull &x) {
    int i = F(x) & (LEN - 1);
    while (ver[i] == cur_ver && key[i] != x)
        i = (i + 1) & (LEN - 1);
    if (ver[i] != cur_ver) {
        ver[i] = cur_ver;
        key[i] = x;
        value[i] = 0;    
    }
    return i;
    }

	ull &operator[](const ull &x) {
		return value[gt(x)];
	}

	inline void clear() {
		if (++cur_ver == INT_MAX) {
			cur_ver = 1;
			memset(ver, 0, sizeof(ver));
		}
	}
} mp;
const int W = 1e9 + 10;
//mp[i * W + j] i 相邻的 j 的 c 和
int gt(int i, int j) {
    return i * W + j;
}
void main() {

    ios::sync_with_stdio(false);
    cin.tie(nullptr);cout.tie(nullptr);
    int t; cin >> t;
    while(t--) {
        mp.clear();
        int sum = 0;
        cin >> n >> q;
        for(int i = 1; i <= n; i++) cin >> a[i], d[i] = 0, p[i].clear(), g[i].clear();
        for(int i = 1; i < n; i++) {
            int u, v, w; cin >> u >> v >> w;
            d[u]++;
            d[v]++;
            p[u].push_back({v, w});
            p[v].push_back({u, w});
            sum += w;
            mp[gt(u, a[v])] += w;
            mp[gt(v, a[u])] += w;
        }
        int dw = 0;
        for(int i = 1; i <= n; i++)
            for(auto [j, w] : p[i]) if(j < i && a[i] == a[j])
                dw += w; 
        for(int i = 1; i <= n; i++)
            for(auto [j, w] : p[i])
                if(d[j] > B) g[i].push_back({j, w});
        while(q--) {
            int u, x; cin >> u >> x;
            if(d[u] <= B) {
                for(auto [v, w] : p[u]) 
                    if(a[v] == a[u]) dw -= w;
                for(auto [v, w] : p[u]) 
                    if(a[v] == x) dw += w;
            } else dw = dw - mp[gt(u, a[u])] + mp[gt(u, x)];
            for(auto [v, w] : g[u]) {
                mp[gt(v, a[u])] -= w;
                mp[gt(v, x)] += w;
            }
            a[u] = x;
            cout << sum - dw << '\n';
        }
        
        
    }

}

#undef int

}


int main()
{
    z::main();
    return 0;
}
2025/7/19 12:04
加载中...