Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- int Left(int i){
- return 2*i+1;
- }
- int Right(int i){
- return 2*i+2;
- }
- int MaxDifHeap(vector <int> H,int index){
- int max=-1,n=H.size();
- if(index<n){
- int lChild=Left(index);
- if(lChild<n){
- int Lmax=H[index]-H[lChild];
- if(Lmax>max)
- max=Lmax;
- int MaxSottalberoLeft=MaxDifHeap(H,lChild);
- if(max<MaxSottalberoLeft)
- max=MaxSottalberoLeft;
- }
- int rChild=Right(index);
- if(rChild<n){
- int Rmax=H[index]-H[rChild];
- if(Rmax>max)
- max=Rmax;
- int MaxSottalberoRight=MaxDifHeap(H,rChild);
- if(max<MaxSottalberoRight)
- max=MaxSottalberoRight;
- }
- }
- return max;
- }
- /*int MaxNodoDifHeap(vector <int> H,int index,int &maxIndex){
- int max=-1,n=H.size();
- if(index<n){
- int lChild=Left(index);
- if(lChild<n){
- int Lmax=H[index]-H[lChild];
- if(Lmax>max){
- max=Lmax;
- maxIndex=index;
- }
- int MaxSottalberoLeft=MaxNodoDifHeap(H,lChild,maxIndex);
- if(max<MaxSottalberoLeft)
- max=MaxSottalberoLeft;
- }
- int rChild=Right(index);
- if(rChild<n){
- int Rmax=H[index]-H[rChild];
- if(Rmax>max){
- max=Rmax;
- maxIndex=index;
- }
- int MaxSottalberoRight=MaxNodoDifHeap(H,rChild,maxIndex);
- if(max<MaxSottalberoRight)
- max=MaxSottalberoRight;
- }
- }
- return max;
- }*/
- int MaxNodoDifHeap(vector <int> H,int index,int &max){
- int maxIndex=-1,n=H.size();
- if(index<n){
- int lChild=Left(index);
- if(lChild<n){
- int LmaxDiff=H[index]-H[lChild];
- if(LmaxDiff>max){
- max=LmaxDiff;
- maxIndex=index;
- }
- int MaxSottalberoLeft=-1,MaxLIndex;
- MaxLIndex=MaxNodoDifHeap(H,lChild,MaxSottalberoLeft);
- if(max<MaxSottalberoLeft){
- max=MaxSottalberoLeft;
- maxIndex=MaxLIndex;
- }
- }
- int rChild=Right(index);
- if(rChild<n){
- int RmaxDiff=H[index]-H[rChild];
- if(RmaxDiff>max){
- max=RmaxDiff;
- maxIndex=index;
- }
- int MaxSottalberoRight=-1,MaxRIndex;
- MaxRIndex=MaxNodoDifHeap(H,rChild,MaxSottalberoRight);
- if(max<MaxSottalberoRight){
- max=MaxSottalberoRight;
- maxIndex=MaxRIndex;
- }
- }
- }
- return maxIndex;
- }
- int main(){
- vector <int> H{10,9,8,4,6,5,1};
- ///int maxNodo=-1;
- int maxDif=-1;
- cout<<"Differenza massima: "<<MaxDifHeap(H,0)<<endl;
- cout<<"Massima differenza fra nodo e figlio si verifica all'indice: "<<MaxNodoDifHeap(H,0,maxDif)<<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement