标签:dfs style cstring lan include int memset vector break
题目链接:http://hihocoder.com/problemset/problem/1616
题解:就是简单的模拟一下至于如何判断是不是二叉搜索树可以通过中序遍历将每个点存下来看是不是递增的如果是递增的就是反之不是
#include <iostream> #include <cstring> #include <cstdio> #include <vector> #include <algorithm> using namespace std; const int M = 1e4 + 10; vector<int> vc[M]; int fa[M] , ch[M][2] , f[M] , n , emmm , num[M]; void init() { for(int i = 1 ; i <= n ; i++) { f[i] = i; vc[i].clear(); } } int find(int x) { if(x == f[x]) return f[x]; return f[x] = find(f[x]); } int cnt; void cau(int u) { int len = vc[u].size(); if(len == 2) { if(vc[u][0] == vc[u][1] || vc[u][0] == u || vc[u][1] == u) emmm = 1; cau(vc[u][0]); num[cnt++] = u; cau(vc[u][1]); } if(len == 1) { if(vc[u][0] == u) emmm = 1; if(vc[u][0] > u) { num[cnt++] = u; cau(vc[u][0]); } else { cau(vc[u][0]); num[cnt++] = u; } } if(len == 0) { num[cnt++] = u; } } void dfs(int u) { int len = vc[u].size(); if(len == 1) { if(u > vc[u][0]) { putchar(‘(‘); printf("%d" , vc[u][0]); dfs(vc[u][0]); putchar(‘)‘); putchar(‘(‘); putchar(‘)‘); } else { putchar(‘(‘); putchar(‘)‘); putchar(‘(‘); printf("%d" , vc[u][0]); dfs(vc[u][0]); putchar(‘)‘); } } if(len == 2) { putchar(‘(‘); printf("%d" , vc[u][0]); dfs(vc[u][0]); putchar(‘)‘); putchar(‘(‘); printf("%d" , vc[u][1]); dfs(vc[u][1]); putchar(‘)‘); } if(len == 0) { putchar(‘(‘); putchar(‘)‘); putchar(‘(‘); putchar(‘)‘); } } int main() { int t; scanf("%d" , &t); while(t--) { cnt = 0; scanf("%d" , &n); memset(fa , -1 , sizeof(fa)); int flag = 0; init(); for(int i = 1 ; i <= n - 1 ; i++) { int u , v; scanf("%d%d" , &u , &v); vc[u].push_back(v); int a = find(u) , b = find(v); if(a == b) { flag = 1; } else { f[b] = a; } if(fa[v] == -1) { fa[v] = u; continue; } else { flag = 1; } } if(flag) { printf("ERROR1\n"); } else { int tmp = 0; for(int i = 1 ; i <= n ; i++) { if(vc[i].size() == 0) continue; sort(vc[i].begin() , vc[i].end()); if(vc[i].size() > 2) { tmp = 1; break; } } if(tmp) { printf("ERROR2\n"); } else { emmm = 0; int root = 1; for(int i = 1 ; i <= n ; i++) { if(fa[i] == -1) { root = i; break; } } cau(root); for(int i = 1 ; i < cnt ; i++) { if(num[i] <= num[i - 1]) { emmm = 1; break; } } if(emmm) { printf("ERROR3\n"); } else { putchar(‘(‘); printf("%d" , root); dfs(root); putchar(‘)‘); puts(""); } } } } return 0; }
标签:dfs style cstring lan include int memset vector break
原文地址:http://www.cnblogs.com/TnT2333333/p/7750042.html