一、二叉平衡树
#include <bits/stdc++.h>
using namespace std;
typedef struct Node *Bintree;
struct Node
{
int v, height; //v为结点权值
Bintree left, right;
};
Bintree newNode(int v)
{
Bintree node = (Bintree)malloc(sizeof(struct Node));
node->v = v;
node->height = 1;
node->left = NULL;
node->right = NULL;
return node;
}
int getHeight(Bintree root)
{
if (root == NULL)
return 0;
else
return root->height;
}
int getBalanceFactor(Bintree root)
{
return getHeight(root->left) - getHeight(root->right);
}
void updateHeight(Bintree root)
{
root->height = max(getHeight(root->left), getHeight(root->right))+1;
}
//平衡二叉树的基本操作
//1. 查找操作 对于平衡二叉树而言,查找操作的复杂度为O(log n) 是二叉查找树
//找到并打印
void find(Bintree root, int x)
{
if (root == NULL)
return;
else
{
if (root->v == x)
printf("%d", root->v);
else if(x<root->v)
find(root->left,x);
else find(root->right,x);
}
}
void L(Bintree &root)
{
Bintree temp=root->right;
root->right=temp->left;
temp->left=root;
updateHeight(root);
updateHeight(temp);
root=temp;
}
void R(Bintree &root)
{
Bintree temp=root->left;
root->left=temp->right;
temp->right=root;
updateHeight(root);
updateHeight(temp);
root=temp;
}
void insert(Bintree &root,int v)
{
if(root==NULL)
{
root=newNode(v);
return;
}
if(v<root->v)
{
insert(root->left,v);
updateHeight(root);
if(getBalanceFactor(root)==2)
{
if(getBalanceFactor(root->left)==1) //LL
{
R(root);
}
else if(getBalanceFactor(root->left)==-1) //LR
{
L(root->left);
R(root);
}
}
}
else if(v>root->v)
{
insert(root->right,v);
updateHeight(root);
if(getBalanceFactor(root)==-2)
{
if(getBalanceFactor(root->right)==-1)//RR
{
L(root);
}
else if(getBalanceFactor(root->right)==1)//RL
{
R(root->right);
L(root);
}
}
}
}
Bintree CreateAVL(int data[],int n)
{
Bintree root=NULL;
for(int i=0;i<n;i++)
{
insert(root,data[i]);
}
return root;
}
二、DAG最长路(DP+递归)
令dp[i]表示从i号顶点出发能获得的最长路径长度,这样所有dp[i]的最大值就是整个DAG的最长路径长度
递归法
#include<bits/stdc++.h>
using namespace std;
const int maxn=100;
const int INF=1000000;
int n;
int G[maxn][maxn];
int dp[maxn]; //主函数中初始化为0
int choice[maxn];//初始化为-1
//求DAG中最长路径长度并输出路径(字典序小优先)
int DP(int i)
{
if(dp[i]>0) return dp[i];
for(int j=0;j<n;j++)
{
if(G[i][j]!=INF)
{
int temp=DP(j)+G[i][j];// DP(j)返回过来的就是计算好的dp[j]
if(temp>dp[i])
{
dp[i]=temp;
choice[i]=j;
}
}
}
return dp[i];
}
//调用printPath之前需要先得到最大的dp[i],然后将i作为路径起点传入
void printPath(int i)
{
printf("%d",i);
while(choice[i]!=-1)
{
i=choice[i];
printf("->%d",i);
}
}
//固定终点,求DAG的最长路径长度
bool vis[maxn];
int DP(int i)
{
if(vis[i]) return dp[i];
vis[i]=true;
for(int j=0;j<n;j++)
{
if(G[i][j]!=INF)
{
dp[i]=max(dp[i],DP(j)+G[i][j]);
}
}
return dp[i];
}