Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #include "testlib.h"
- using namespace std;
- const int MAXN = 2010;
- int n;
- int orig_tree[MAXN];
- string orig_hash;
- vector<int> child[MAXN];
- bool vis[MAXN];
- bool hascycle;
- string dfs(int root) {
- if (vis[root]) {
- hascycle = true;
- return "";
- }
- vis[root] = true;
- if (child[root].size() == 0) {
- return "()";
- }
- string a[2];
- int aidx = 0;
- for (auto x : child[root]) {
- a[aidx++] = dfs(x);
- }
- if (a[0] > a[1]) {
- return "(" + a[1] + a[0] + ")";
- } else {
- return "(" + a[0] + a[1] + ")";
- }
- }
- string getHash(int tree[]) {
- hascycle = false;
- for (int i = 1; i <= 2 * n - 1; i++) {
- child[i].clear();
- vis[i] = false;
- }
- int root = -1;
- for (int i = 1; i <= 2 * n - 1; i++) {
- if (tree[i] == -1) {
- root = i;
- } else {
- child[tree[i]].push_back(i);
- }
- }
- return dfs(root);
- }
- inline int readAns(InStream& in) {
- int qs = in.readInt();
- if (qs > 10 * n) {
- in.quitf(_wa, "Too many questions %d", qs);
- }
- int tree[MAXN];
- int used[MAXN];
- for (int i = 0; i <= 2 * n - 1; i++) used[i] = 0;
- int root = -1;
- for (int i = 1; i <= 2 * n - 1; i++) {
- tree[i] = in.readInt(-1, 2*n-1);
- if (tree[i] == 0) {
- in.quitf(_wa, "label of parent should be between 1 and 2*n-1");
- }
- if (tree[i] == -1) {
- if (root != -1) {
- in.quitf(_wa, "Found multiple roots %d %d", i, root);
- }
- root = i;
- } else {
- used[tree[i]]++;
- }
- }
- if (root == -1) {
- in.quitf(_wa, "Didn't find a root");
- }
- for (int i = 1; i <= 2 * n - 1; i++) {
- if (used[i] != 0 && used[i] != 2) {
- in.quitf(_wa, "Each node must have exactly 0 or 2 children %d %d", i, used[i]);
- }
- }
- string c_hash = getHash(tree);
- if (hascycle) {
- in.quitf(_wa, "Output has cycles");
- }
- for (int i = 1; i <= 2 * n - 1; i++) {
- if (!vis[i]) {
- in.quitf(_wa, "Not all nodes reachable from root.");
- }
- }
- if (orig_hash != c_hash) {
- in.quitf(_wa, "Trees are not isomorphic");
- }
- return qs;
- }
- int main(int argc, char* argv[]) {
- registerTestlibCmd(argc, argv);
- n = inf.readInt();
- for (int i = 1; i <= 2 * n - 1; i++) {
- orig_tree[i] = inf.readInt();
- }
- orig_hash = getHash(orig_tree);
- int a = readAns(ans);
- int b = readAns(ouf);
- quitf(_ok, "Found tree in %d questions!", b);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement