The main topic: give some strings to represent the binary tree, the format of the string is as follows (N,s), n is the number on the node, s indicates where the node is, ask whether these strings can be composed of two fork tree
Problem-solving ideas: can form two fork tree, the first need to determine the root node.
Then judge the other nodes, in the order of the hierarchical traversal to enumerate, so to sort first, by the length of the string to sort.
If the node can be a two-tree node, then his parent node will exist.
To determine if his parent is present, simply determine if the string of characters consisting of his former len-1 (len indicates length) exists
The problem is to be weighed.
#include <cstdio>#include <cstring>#include <algorithm>#include <map>#include <string>using namespace STD;#define MAXN 266structnode{intNum, Len;CharSTR[MAXN];} N[MAXN];intANS[MAXN], CNT;BOOLSolve () {intCount =0, M =1, start =0; Map<string,int>Map;if(n[0].len! =1) {return false; }Else{ans[count++] = n[0].num; Start =1; } for(inti = start; I < CNT; i++) {if(N[i].len = =1)return false;stringTif(N[i].len = =2) {stringT T + = n[i].str[0];if(Map[t])return false; Map[t] = m++; ans[count++] = N[i].num;Continue; } for(intj =0; J < N[i].len-2; J + +) T + = n[i].str[j];if(Map[t]) ans[count++] = N[i].num;Else return false; T + = N[i].str[n[i].len-2];if(Map[t])return false; Map[t] = m++; }return true;}BOOLcmpConstNode A,ConstNode b) {if(A.len = = B.len)return strcmp(B.STR,A.STR) >0;Else returnA.len < B.len;}intMain () {CharSTR[MAXN]; while(scanf('%s ', str)! = EOF) {cnt =0;if(strcmp(STR,"()") ==0) Break;sscanf(STR,"(%d,%s)", &N[CNT].NUM,N[CNT].STR); N[cnt].len =strlen(N[CNT].STR); cnt++; while(scanf('%s ', str)! = EOF) {if(strcmp(STR,"()") ==0) Break;sscanf(STR,"(%d,%s)", &n[cnt].num, N[CNT].STR); N[cnt].len =strlen(N[CNT].STR); cnt++; } sort (n, n + CNT, CMP);if(Solve ()) {printf("%d", ans[0]); for(inti =1; I < CNT; i++)printf("%d", Ans[i]); }Else printf(" not Complete");printf("\ n"); }return 0;}
UVA-122 Trees on the level Map