蓝题训练9.13P7323 [WC2021] 括号路径

P7323 [WC2021] 括号路径
https://www.luogu.com.cn/problem/P7323
Tagstl 思维
题意:略

题解:善用stl配合并查集维护合并关系

参考代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll p=998244353;
ll n,m,k;
queue<pair<ll,ll>> q;
map<ll,ll> mp[300005];
struct DSU {
	std::vector<ll> pa, size;

	explicit DSU(ll size_) : pa(size_), size(size_, 1) {
		std::iota(pa.begin(), pa.end(), 0);
	}

	size_t find(ll x) {
		return pa[x] == x ? x : pa[x] = find(pa[x]);
	}

	void unite(ll x, ll y) {
		x = find(x), y = find(y);
		if (x == y) return;
		if (size[x] < size[y]) std::swap(x, y);
		pa[y] = x;
		size[x] += size[y];
		for(map<ll,ll>::iterator it=mp[y].begin(); it!=mp[y].end(); it++) {
			if(mp[x][it->first]) q.push({it->second,mp[x][it->first]});
			else mp[x][it->first]=it->second;
		}
	}
};
void solve() {
	cin>>n>>m>>k;
	DSU V(n+1);
	for(int i=1,u,v,w; i<=m; i++) {
		cin>>u>>v>>w;
		if(mp[v].find(w)==mp[v].end()) mp[v][w]=u;
		else q.push({u,mp[v][w]});
	}
	while(!q.empty()) {
		ll u=q.front().first,v=q.front().second;
		q.pop();
		V.unite(u,v);
	}
	ll ans=0;
	for(int i=1;i<=n;i++) if(i==V.pa[i]) ans+=(ll)V.size[i]*(V.size[i]-1)/2;
	cout<<ans;
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	ll T=1;
	while(T--) solve();
	return 0;
}


posted @ 2026-09-14 00:27  pigeon666  阅读(2)  评论(0)    收藏  举报