Wa 11 pts 带权并查集 悬关
查看原帖
Wa 11 pts 带权并查集 悬关
689640
Michael2012楼主2025/8/1 23:07
#include <iostream>
using namespace std;
const int N = 105 , M = 1e3 + 5;
int n , m , f[N] , g[N];
int find(int x){
	if (f[x] == x) return x;
	find(f[x]);
	g[x] += g[f[x]];
	return f[x] = f[f[x]];
}
int main(){
	int cases;
	cin >> cases;
	while (cases--){
		cin >> n >> m;
		for (int i = 0;i <= n;i++) f[i] = i , g[i] = 0;
		int x , y , z;
		bool flag = 1;
		while (m--){
			cin >> x >> y >> z;
			--x;
			if (find(x) == find(y)){
                // cout << "#\n";
				if (g[x] != g[y] + z){
					flag = 0;
				}
				continue;
			}
			f[f[x]] = f[y];
			g[f[x]] = z - g[x] + g[y];
            // for (int i = 1;i <= n;i++){
            //     cout << find(i) << ' ';
            //     cout << g[i] << '\n';
            // }
		}
		cout << (flag ? "true" : "false") << '\n';
	}
	return 0;
}
2025/8/1 23:07
加载中...