C语言指针实现左偏树求助,代码如下
查看原帖
C语言指针实现左偏树求助,代码如下
587036
LightChaser楼主2022/4/10 17:26
#include<stdio.h>
#include<stdlib.h>
struct TreeNode{
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    int npl;
    int num;//记录第几个输入
};

int input[ 100010 ];//第i个值为第i个输入的值所在堆在“堆数组”中的位置
int deleted[ 100010 ];//记录每个输入的被删除情况
struct TreeNode *a[ 100010 ];

struct TreeNode* mergeNode( struct TreeNode *H1, struct TreeNode *H2 );
struct TreeNode* merge( struct TreeNode* H1, struct TreeNode* H2 )
{
    if( H1->left == NULL )
        H1->left = H2;
    else
    {
        H1->right = mergeNode( H1->right, H2 );
        if( H1->left->npl < H1->right->npl )
        {
            struct TreeNode *tmp = H1->left;
            H1->left = H1->right;
            H1->right = tmp;
        }
        H1->npl = H1->right->npl + 1;
    }

    return H1;
}
struct TreeNode* mergeNode( struct TreeNode *H1, struct TreeNode *H2 )
{
    if( H1 == NULL )
        return H2;
    if( H2 == NULL )
        return H1;
    
    if( H1->val < H2->val )
        return merge( H1, H2 );
    else
        return merge( H2, H1 );
}
int findMin( struct TreeNode *H, int x )
{
    if( deleted[ x ] )
        return -1;
    int ans = H->val;
    if( H->num == x )//即将被删除的数就是第x个输入的数
        deleted[ x ] = 1;
    struct TreeNode *tmp = H;
    H = mergeNode( H->left, H->right );
    a[ input[ x ] ] = H;//因为合并后的输入元素input[i]值相同,只需修改a[ input[ x ] ]处的堆地址
    free( tmp );
    return ans;
}
void freeHeap( struct TreeNode *H )
{
    if( H == NULL )
        return ;
    freeHeap( H->left );
    freeHeap( H->right );
    free( H );
}
int main()
{
    int n, m;
    scanf("%d%d", &n, &m );
    int i;
    for( i = 1; i <= n; i++ )
    {
        deleted[ i ] = 0;
        input[ i ] = i;
        a[ i ] = ( struct TreeNode* )malloc( sizeof( struct TreeNode ) );
        scanf("%d", &a[ i ]->val );
        a[ i ]->left = NULL;
        a[ i ]->right = NULL;
        a[ i ]->npl = 0;
        a[ i ]->num = i;
    }
    int x, y, op;
    for( i = 0; i < m; i++ )
    {
        scanf("%d%d", &op, &x );
        if( op == 1 )
        {
            scanf("%d", &y );
            if( input[ x ] < input[ y ] )
            {
                a[ input[ x ] ] = mergeNode( a[ input[ x ] ], a[ input[ y ] ] );
                a[ input[ y ] ] = a[ input[ x ] ];
                input[ y ] = input[ x ];
            }
            else
            {
                a[ input[ y ] ] = mergeNode( a[ input[ x ] ], a[ input[ y ] ] );
                a[ input[ x ] ] = a[ input[ y ] ];
                input[ x ] = input[ y ];
            }
        }
        else
        {
            printf("%d\n", findMin( a[ input[ x ] ], x ) );
        }
    }
    for( i = 1; i <= n; i++ )
    {
        freeHeap( a[ input[ i ] ] );
        a[ input[ i ] ] = NULL;
    }
        
    return 0;
}
2022/4/10 17:26
加载中...