#include #include #include #include #include #include #include #include #include #include #include using namespace std; void fail(const char* msg = NULL) { if (msg) { cout << "fail: " << msg << endl; } else { cout << "fail" << endl; } exit(1); } void fassert(bool cond, const char* msg = NULL) { if (!cond) { fail(msg); } } struct input { input(FILE* f) : uch(-2), fin(f), sin(NULL), read_bytes(0) { } input(istream& in) : uch(-2), fin(NULL), sin(&in), read_bytes(0) { } int get() { if (uch != -2) { int ch = uch; uch = -2; return ch; } else if (fin) { read_bytes++; return fgetc(fin); } return sin->get(); } void unget(int ch) { uch = ch; } char get_char() { int ch = get(); if (ch == -1) { fail("expected char"); } else if (ch != '\n' && (ch < 32 || 126 < ch)) { fail("expected printable ascii"); } return ch; } void get_eof() { fassert(get() == -1, "expected eof"); } void get_eol() { fassert(get() == '\n', "expected eol"); } void get_space() { fassert(get() == ' ', "expected space"); } void get_spaces() { int ch; get_space(); for (ch = get(); ch == ' '; ch = get()); unget(ch); } string get_token() { int ch; string res; for (ch = get(); ch != -1 && ch != '\n' && ch != ' '; ch = get()) { res += (char)ch; } fassert(!res.empty(), "expected token"); unget(ch); return res; } long long get_int(long long min, long long max, const char* msg = NULL) { string tok = get_token(); long long res = atoll(tok.c_str()); fassert(tok == to_string(res), "expected int"); if(msg) fassert(min <= res && res <= max, msg); else fassert(min <= res && res <= max, "int out of range"); return res; } double get_double(double min, double max, const char* msg = NULL) { string tok = get_token(); double res = atof(tok.c_str()); if(msg) fassert(min <= res && res <= max, msg); else fassert(min <= res && res <= max, "double out of range"); return res; } string get_line(int min_length, int max_length, const char* lmsg = NULL, const char* gmsg = NULL) { int ch; string res; for (ch = get(); ch != -1 && ch != '\n'; ch = get()) { res += (char)ch; if((int)res.size() > max_length) { if(gmsg) fail(gmsg); else fail("line too long"); } } if((int)res.size() < min_length) { if(lmsg) fail(lmsg); else fail("line too short"); } unget(ch); return res; } int uch; FILE* fin; istream* sin; int read_bytes; }; int par[200005]; int find(int x) { return par[x] == x ? x : (par[x] = find(par[x])); } void merge(int x, int y) { par[find(x)] = find(y); } int main(int argc, char** argv) { input in(cin); int n = in.get_int(1, 50000, "n outside range from 1 to 5 * 10^4"); in.get_eol(); for(int i = 1; i <= n; i++) { par[i] = i; } for(int qq = 1; qq < n; qq++) { int a = in.get_int(1, n, "a outside range from 1 to n"); in.get_space(); int b = in.get_int(1, n, "b outside range from 1 to n"); in.get_space(); in.get_int(1, n, "c outside range from 1 to n"); in.get_eol(); fassert(find(a) != find(b), "cycle detected"); merge(a, b); } in.get_eof(); return 42; }