现在的位置: 首页 > 综合 > 正文

信号放大器算法(在二叉树节点中放最少放大器,并保证所有节点信号量不至于过低)

2013年06月09日 ⁄ 综合 ⁄ 共 1472字 ⁄ 字号 评论关闭

题目: 输入一个二叉树网络,每个节点有一个从父亲节点到本节点的衰减值,树根为信号的源头,希望在二叉树中放置尽可能少的放大器,并且所有节点的信号量衰减值不超过一个容忍值。放大器可以将信号放大到树根节点出发时候的信号量大小。

算法思想:采用后序遍历,在遍历过程中判断是否需要加放大器。

算法正确性: 因为后续遍历可以将同一层上(兄弟间)需要加放大器的节点,合并到父亲节点中,从而达到了减少放大器数量的目的。

#include <iostream>

#include <stack>

using namespace std;
int MaxReduction=0;
struct Node{
int num;//节点编号
int reduction;//到父节点之间 的衰减
int maxReduction;//到所有子节点之间的 最大衰减
bool flag;//是否添加放大器
Node * left;
Node * right;
};
void Create(Node * & root)
{
int t,s;
cin>>t;
if(t==-1)
return;
cin>>s;
root=new Node;
root->num=t;
root->reduction=s;
root->flag=false;
root->maxReduction=0;
root->left=root->right=NULL;
Create(root->left);
Create(root->right);
}
void PostTraverse(Node * root)
{
if(root==NULL)return;
PostTraverse(root->left);
PostTraverse(root->right);
if(root->left)
{
if(root->left->maxReduction+root->left->reduction>=MaxReduction)
root->left->flag=true;
else
{
if(root->left->maxReduction+root->left->reduction>root->maxReduction)
root->maxReduction=root->left->maxReduction+root->left->reduction;
}
}
if(root->right)
{
if(root->right->maxReduction+root->right->reduction>=MaxReduction)
root->right->flag=true;
else
{
if(root->right->maxReduction+root->right->reduction>root->maxReduction)
root->maxReduction=root->right->maxReduction+root->right->reduction;
}
}

}
void Show(Node * root)
{
if(root==NULL)
return;
if(root->flag)
cout<<"节点"<<root->num<<" 放置放大器"<<endl;
Show(root->left);
Show(root->right);

}
void main()
{
cout<<"请输入最大衰减值\n";
cin>>MaxReduction;
cout<<"请输入二叉树\n";
Node * root;
Create(root);
PostTraverse(root);//后序遍历过程中 确定何处加放大器
Show(root);

::system("pause");

}

抱歉!评论已关闭.