此题来自白书数据结构基础二叉树的训练参考
翻译请戳 http://luckycat.kshs.kh.edu.tw/
uva的翻译幸运猫里大部分有
解题思路
建树的思想跟白书里的是一样的,虽然此题给的是中序和后序遍历。
虽然节点最多有10000个,递归建树可能会栈溢出。。。但是依然AC了。。。
最后BFS整棵树就行啦。
代码
#include<stdio.h> #define MAX_SIZE 10001 //#define LOCAL typedef struct node { int value, tot; struct node *lchild, *rchild; }Node; int LOrder[MAX_SIZE], pL; int MOrder[MAX_SIZE], pM; Node *q[MAX_SIZE]; //char s[1000001]; bool ReadS() { char ch; while((ch=getchar())==‘ ‘) ; if(ch==EOF) return false; while(ch != ‘\n‘) { ungetc(ch, stdin); int d; scanf("%d", &d); MOrder[++pM] = d; while((ch=getchar())==‘ ‘) ; } ch = getchar(); // while(ch==‘ ‘) ch = getchar(); while(ch != ‘\n‘) { ungetc(ch, stdin); int d; scanf("%d", &d); LOrder[++pL] = d; while((ch=getchar())==‘ ‘) ; } return true; } int FindRoot(int l, int r) { for(int i=l; i<=r; i++) if(MOrder[i] == LOrder[pL]) return i; } void NewNode(Node *&root, int i) { root = new Node; root->value = MOrder[i]; root->tot = root->value; root->lchild = root->rchild = NULL; } void Build(Node *&root, int l, int r) { if(l>r) { root = NULL; pL++; return ; } int i=FindRoot(l, r); NewNode(root, i); pL--; Build(root->rchild, i+1, r); pL--; Build(root->lchild, l, i-1); } void BFS(Node *root) { int front, rear; Node* minNode; int minTot = 1e9; front = rear = MAX_SIZE - 1; rear = (rear+1) % MAX_SIZE; q[rear] = root; while(rear != front) { front=(front+1)%MAX_SIZE; if(q[front]->lchild != NULL) { rear=(rear+1)%MAX_SIZE; q[rear] = q[front]->lchild; q[rear]->tot += q[front]->tot; if(q[rear]->lchild==NULL&&q[rear]->rchild==NULL) if(q[rear]->tot < minTot) { minNode = q[rear]; minTot = minNode->tot; } } if(q[front]->rchild != NULL) { rear=(rear+1)%MAX_SIZE; q[rear] = q[front]->rchild; q[rear]->tot += q[front]->tot; if(q[rear]->lchild==NULL&&q[rear]->rchild==NULL) if(q[rear]->tot < minTot) { minNode = q[rear]; minTot = minNode->tot; } } if(q[front]->lchild==NULL&&q[front]->rchild==NULL&&q[front]->tot<minTot) { minNode = q[front]; minTot = minNode->tot; } } printf("%d\n", minNode->value); } int main() { #ifdef LOCAL freopen("data.txt", "r", stdin); freopen("ans.txt", "w", stdout); #endif while(ReadS()) { Node *root = NULL; Build(root, 1, pL); BFS(root); pM = pL = 0; } return 0; }
时间: 2024-10-06 02:51:50