[Data structures]Second optimal search tree
#include <stdio.h> #include <stdlib.h> typedef struct _BinaryTree{ int key; struct _BinaryTree *left; struct _BinaryTree *right; }BinaryTree; /* seq[] from 1 to n; sw[0] = 0 */ void secondOptimal(BinaryTree **T, int seq[], float sw[], int low, int high) { BinaryTree *p=NULL; int i = low; float min = abs(sw[high] - sw[low-1]); float dp = 0; int j; for(j = low+1; j < high; j++){ dp = abs( (sw[high] - sw[j]) - (sw[j-1] - sw[low-1]) ); if(min > dp ){ min = dp; i = j; } } p = (BinaryTree *)malloc( sizeof(BinaryTree) ); *T = p; p->key = seq[i]; if( i == low ){ p->left = NULL; }else{ secondOptimal(&(p->left), seq, sw, low, i-1); } if( i == high ){ p->right = NULL; }else{ secondOptimal(&(p->right), seq, sw, i+1, high); } } void printTree(BinaryTree *T){ if(T == NULL){ return; } printf(" %c", T->key ); printf("("); if(T->left != NULL){ printTree(T->left); } printf(","); if(T->right != NULL){ printTree(T->right); } printf(")"); } void main() { int seq[] = { 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'}; float w[] = { 0, 1 , 1 , 2 , 5 , 3 , 4 , 4 , 3 , 5 }; float *sw; int n = sizeof(seq)/sizeof(int); int i; BinaryTree *T = NULL; sw = (float *)malloc(sizeof(float) * n); /* Create the sum weight, sw[0] = 0; */ sw[0] = 0; for(i=1; i<=n; i++){ sw[i] = sw[i-1] + w[i]; } printf("Original data:\n"); for (i=0; i<n; i++) { printf("%c\t", seq[i]); } printf("\n"); for (i=0; i<n; i++) { printf("%02.2f\t", w[i]); } printf("\n"); for (i=0; i<n; i++) { printf("%02.2f\t", sw[i]); } printf("\n"); printf("Create second optimal tree:\n"); secondOptimal(&T, seq, sw, 1, n-1); printf("Print the tree:\n"); printTree(T); printf("\n"); }
日历
最新微语
- 有的时候,会站在分叉路口,不知道向左还是右
2023-12-26 15:34
- 繁花乱开,鸟雀逐风。心自宁静,纷扰不闻。
2023-03-14 09:56
- 对于不可控的事,我们保持乐观,对于可控的事情,我们保持谨慎。
2023-02-09 11:03
- 小时候,
暑假意味着无忧无虑地玩很长一段时间,
节假意味着好吃好喝还有很多长期不见的小朋友来玩...
长大后,
这是女儿第一个暑假,
一个半月...
2022-07-11 08:54
- Watching the autumn leaves falling as you grow older together
2018-10-25 09:45
分类
最新评论
- Goonog
i get it now :) - 萧
@Fluzak:The web host... - Fluzak
Nice blog here! Also... - Albertarive
In my opinion you co... - ChesterHep
What does it plan? - ChesterHep
No, opposite. - mojoheadz
Everything is OK!... - Josephmaigh
I just want to say t... - ChesterHep
What good topic - AnthonyBub
Certainly, never it ...
发表评论: