#include #include "testlib.h" using namespace std; struct Union_find { vector par; //親 vector siz; //根ノードiの木に含まれる要素数。iが根ノード出ない場合無意味な値となる。 //n要素で初期化 Union_find(int n) { par.resize(n); siz.resize(n); for(int i = 0;i < n;i++) { par[i] = i; siz[i] = 1; } } //木の根を求める int find(int x) { if(par[x] == x) { return x; } else { return par[x] = find(par[x]); } } //xとyの属する集合を併合 void unite(int x,int y) { x = find(x); y = find(y); if(x == y) { return; } if(siz[x] < siz[y]) { swap(x,y); } par[y] = x; siz[x] += siz[y]; } //xとyが同じ集合に属するか否か bool same(int x,int y) { return find(x) == find(y); } int size(int x) { return siz[find(x)]; } }; //A,空白,B,改行の順に読み込み(1 <= A,B <= 100) int main(int argc,char* argv[]) { registerValidation(argc,argv); int N = inf.readInt(2,100,"N"); inf.readSpace(); int K = inf.readInt(1,100000,"K"); inf.readEoln(); set> edges; Union_find uf(N + 1); for(int i = 0;i < N - 1;i++) { int a = inf.readInt(1,N); inf.readSpace(); int b = inf.readInt(1,N); inf.readSpace(); int c = inf.readInt(1,K); inf.readEoln(); ensuref(a != b,"Tree can't contain loops"); ensuref(!edges.count({a,b}),"Tree can't contain multiple edges between a pair of vertices"); edges.insert({a,b}); edges.insert({b,a}); ensuref(!uf.same(a,b),"Tree can't contain cycles"); uf.unite(a,b); } inf.readEof(); return 0; }