uva 548

#include <iostream>
using namespace std;
#include <string>
#include <sstream>
#include <cstring>
int min1, min2;
int a[10000];
int b[10000];
int sum;
/*struct Node{
char value;
Node * left;
Node * right;
Node(int a = 0) :value(a) {}
};
//根据中序和后续，创建tree
//递归的把后续序列中的最后一个value，当做root节点，并把mid分成两部分，然后back_idx --
//分成两部分后，一定先创建右子树
Node* build_tree(char *mid, int num_pre, char* back, int &back_idx){
if (back_idx < 0 || num_pre == 0)
return NULL;
int i;
char cur_mid = back[back_idx];
for (i = 0; i< num_pre; i++){
if (mid[i] == cur_mid)
break;
}
if (i == num_pre)
return NULL;
else{
Node * root = new Node();
root->value = cur_mid;
back_idx--;
root->right = build_tree(mid + i + 1, num_pre - i - 1, back, back_idx);
root->left = build_tree(mid, i, back, back_idx);
return root;
}

}

void delete_tre(Node * root){ //
if (root != NULL){
delete_tre(root->left);
delete_tre(root->right);
delete root;
}
}
int main(){
char mid[10] = { 'D', 'B', 'G', 'E', 'A', 'C', 'F' };
char back[10] = { 'D', 'G', 'E', 'B', 'F', 'C', 'A' };
int back_idx = 7 - 1; //指向当前back中的最后一个元素
Node * root = build_tree(mid, 7, back, back_idx);
delete_tre(root);
return 0;
}
Node *build_tree(int *a,int numa,int *b,int numb)
{
if (numa == 0 || numb < 0)

return NULL;

int i;
int count = 0;
Node * l = new Node ();
Node *r = new Node();
int mid = b[numb];
for (i = 0; i < numa; i++)
{
if (a[i] == mid)
break;
}
if (i == numa) //没有找到某子树的根节点
return NULL;
else
{
Node *root = new Node();
root->value = mid;
numb--;
root->right = build_tree(a + i + 1,numa - 1 - i,b,numb);
root->left = build_tree(a , i, b, numb); //此处出现了错误
return root;
}
}*/
int find(int k,int *p,int n)
{
int i = 0;
for (i = n - 1; i >= 0; i--)
{
if (p[i] == k)
return i;
}
return 0;
}
void build(int n,int *a,int *b,int sum)
{
int k;
if (n <= 0) return;
k = find(b[n - 1], a, n);
sum = sum + b[n - 1];
if (k <= 0 && n - 1 - k <= 0)
{
if (sum == min1) //判断是否相等 相等的话选择小的哪一个
min2 = (b[n - 1]<min2 ? b[n - 1] : min2);
else if (sum<min1)
{
min1 = sum;
min2 = b[n - 1];
}
return;
}

build(k, a, b, sum);
build(n - 1 - k, a + k+1, b + k , sum);
}
int main()
{
string s1;
string s2;
int i = 0;
//  Node *leaf = new Node();
while (getline(cin,s1))
{
i = 0;
getline(cin, s2);
min1 = 100000;
min2 = 100000;
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
stringstream ss1(s1);
stringstream ss2(s2);
while (ss1 >> a[i])
{
ss2 >> b[i++];
}
build(i, a, b, 0);
printf("%d\n", min2);
}
return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：uva 548 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)