跳到正文

题解

题解 P3378 【【模板】堆】

劉子颺约 35 分钟
原文
文章信息与版本

文章信息

发布
2018年11月28日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 35 分钟
题目
P3378

版本

  1. v2当前
  2. v1

为什么不试试有趣的Hollow 堆 呢? 出自Robert Tarjan的 Hollow Heaps. ACM Trans. Algorithms 13(3): 42:1-42:27 (2017)

C++
#pragma GCC optimize(3)
#ifndef _HOLLOW_HEAP_H_
#define _HOLLOW_HEAP_H_

#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
#include <queue>
#include <cmath>
#define DEBUG -1

#if defined(DEBUG) && DEBUG > 0
#define DEBUG_PRINT(fmt, args...) \
    fprintf(stderr, "DEBUG: %d:%s(): " fmt, __LINE__, __func__, ##args)
#else
#define DEBUG_PRINT(fmt, args...)
#endif

#define hh_node HollowHeapNode<K,I>
namespace fastIO{
    #define BUF_SIZE 100000
    #define OUT_SIZE 100000
    #define ll long long
    //fread->read
    bool IOerror=0;
    inline char nc(){
        static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
        if (p1==pend){
            p1=buf; pend=buf+fread(buf,1,BUF_SIZE,stdin);
            if (pend==p1){IOerror=1;return -1;}
            //{printf("IO error!\n");system("pause");for (;;);exit(0);}
        }
        return *p1++;
    }
    inline bool blank(char ch){return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';}
    inline void read(int &x){
        bool sign=0; char ch=nc(); x=0;
        for (;blank(ch);ch=nc());
        if (IOerror)return;
        if (ch=='-')sign=1,ch=nc();
        for (;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0';
        if (sign)x=-x;
    }
    inline void read(ll &x){
        bool sign=0; char ch=nc(); x=0;
        for (;blank(ch);ch=nc());
        if (IOerror)return;
        if (ch=='-')sign=1,ch=nc();
        for (;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0';
        if (sign)x=-x;
    }
    inline void read(double &x){
        bool sign=0; char ch=nc(); x=0;
        for (;blank(ch);ch=nc());
        if (IOerror)return;
        if (ch=='-')sign=1,ch=nc();
        for (;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0';
        if (ch=='.'){
            double tmp=1; ch=nc();
            for (;ch>='0'&&ch<='9';ch=nc())tmp/=10.0,x+=tmp*(ch-'0');
        }
        if (sign)x=-x;
    }
    inline void read(char *s){
        char ch=nc();
        for (;blank(ch);ch=nc());
        if (IOerror)return;
        for (;!blank(ch)&&!IOerror;ch=nc())*s++=ch;
        *s=0;
    }
    inline void read(char &c){
        for (c=nc();blank(c);c=nc());
        if (IOerror){c=-1;return;}
    }
    //getchar->read
    inline void read1(int &x){
        char ch;int bo=0;x=0;
        for (ch=getchar();ch<'0'||ch>'9';ch=getchar())if (ch=='-')bo=1;
        for (;ch>='0'&&ch<='9';x=x*10+ch-'0',ch=getchar());
        if (bo)x=-x;
    }
    inline void read1(ll &x){
        char ch;int bo=0;x=0;
        for (ch=getchar();ch<'0'||ch>'9';ch=getchar())if (ch=='-')bo=1;
        for (;ch>='0'&&ch<='9';x=x*10+ch-'0',ch=getchar());
        if (bo)x=-x;
    }
    inline void read1(double &x){
        char ch;int bo=0;x=0;
        for (ch=getchar();ch<'0'||ch>'9';ch=getchar())if (ch=='-')bo=1;
        for (;ch>='0'&&ch<='9';x=x*10+ch-'0',ch=getchar());
        if (ch=='.'){
            double tmp=1;
            for (ch=getchar();ch>='0'&&ch<='9';tmp/=10.0,x+=tmp*(ch-'0'),ch=getchar());
        }
        if (bo)x=-x;
    }
    inline void read1(char *s){
        char ch=getchar();
        for (;blank(ch);ch=getchar());
        for (;!blank(ch);ch=getchar())*s++=ch;
        *s=0;
    }
    inline void read1(char &c){for (c=getchar();blank(c);c=getchar());}
    //scanf->read
    inline void read2(int &x){scanf("%d",&x);}
    inline void read2(ll &x){
        #ifdef _WIN32
            scanf("%I64d",&x);
        #else
        #ifdef __linux
            scanf("%lld",&x);
        #else
            puts("error:can't recognize the system!");
        #endif
        #endif
    }
    inline void read2(double &x){scanf("%lf",&x);}
    inline void read2(char *s){scanf("%s",s);}
    inline void read2(char &c){scanf(" %c",&c);}
    inline void readln2(char *s){gets(s);}
    //fwrite->write
    struct Ostream_fwrite{
        char *buf,*p1,*pend;
        Ostream_fwrite(){buf=new char[BUF_SIZE];p1=buf;pend=buf+BUF_SIZE;}
        void out(char ch){
            if (p1==pend){
                fwrite(buf,1,BUF_SIZE,stdout);p1=buf;
            }
            *p1++=ch;
        }
        void print(int x){
            static char s[15],*s1;s1=s;
            if (!x)*s1++='0';if (x<0)out('-'),x=-x;
            while(x)*s1++=x%10+'0',x/=10;
            while(s1--!=s)out(*s1);
        }
        void println(int x){
            static char s[15],*s1;s1=s;
            if (!x)*s1++='0';if (x<0)out('-'),x=-x;
            while(x)*s1++=x%10+'0',x/=10;
            while(s1--!=s)out(*s1); out('\n');
        }
        void print(ll x){
            static char s[25],*s1;s1=s;
            if (!x)*s1++='0';if (x<0)out('-'),x=-x;
            while(x)*s1++=x%10+'0',x/=10;
            while(s1--!=s)out(*s1);
        }
        void println(ll x){
            static char s[25],*s1;s1=s;
            if (!x)*s1++='0';if (x<0)out('-'),x=-x;
            while(x)*s1++=x%10+'0',x/=10;
            while(s1--!=s)out(*s1); out('\n');
        }
        void print(double x,int y){
            static ll mul[]={1,10,100,1000,10000,100000,1000000,10000000,100000000,
                1000000000,10000000000LL,100000000000LL,1000000000000LL,10000000000000LL,
                100000000000000LL,1000000000000000LL,10000000000000000LL,100000000000000000LL};
            if (x<-1e-12)out('-'),x=-x;x*=mul[y];
            ll x1=(ll)floor(x); if (x-floor(x)>=0.5)++x1;
            ll x2=x1/mul[y],x3=x1-x2*mul[y]; print(x2);
            if (y>0){out('.'); for (size_t i=1;i<y&&x3*mul[i]<mul[y];out('0'),++i); print(x3);}
        }
        void println(double x,int y){print(x,y);out('\n');}
        void print(char *s){while (*s)out(*s++);}
        void println(char *s){while (*s)out(*s++);out('\n');}
        void flush(){if (p1!=buf){fwrite(buf,1,p1-buf,stdout);p1=buf;}}
        ~Ostream_fwrite(){flush();}
    }Ostream;
    inline void print(int x){Ostream.print(x);}
    inline void println(int x){Ostream.println(x);}
    inline void print(char x){Ostream.out(x);}
    inline void println(char x){Ostream.out(x);Ostream.out('\n');}
    inline void print(ll x){Ostream.print(x);}
    inline void println(ll x){Ostream.println(x);}
    inline void print(double x,int y){Ostream.print(x,y);}
    inline void println(double x,int y){Ostream.println(x,y);}
    inline void print(char *s){Ostream.print(s);}
    inline void println(char *s){Ostream.println(s);}
    inline void println(){Ostream.out('\n');}
    inline void flush(){Ostream.flush();}
    //puts->write
    char Out[OUT_SIZE],*o=Out;
    inline void print1(int x){
        static char buf[15];
        char *p1=buf;if (!x)*p1++='0';if (x<0)*o++='-',x=-x;
        while(x)*p1++=x%10+'0',x/=10;
        while(p1--!=buf)*o++=*p1;
    }
    inline void println1(int x){print1(x);*o++='\n';}
    inline void print1(ll x){
        static char buf[25];
        char *p1=buf;if (!x)*p1++='0';if (x<0)*o++='-',x=-x;
        while(x)*p1++=x%10+'0',x/=10;
        while(p1--!=buf)*o++=*p1;
    }
    inline void println1(ll x){print1(x);*o++='\n';}
    inline void print1(char c){*o++=c;}
    inline void println1(char c){*o++=c;*o++='\n';}
    inline void print1(char *s){while (*s)*o++=*s++;}
    inline void println1(char *s){print1(s);*o++='\n';}
    inline void println1(){*o++='\n';}
    inline void flush1(){if (o!=Out){if (*(o-1)=='\n')*--o=0;puts(Out);}}
    struct puts_write{
        ~puts_write(){flush1();}
    }_puts;
    inline void print2(int x){printf("%d",x);}
    inline void println2(int x){printf("%d\n",x);}
    inline void print2(char x){printf("%c",x);}
    inline void println2(char x){printf("%c\n",x);}
    inline void print2(ll x){
        #ifdef _WIN32
            printf("%I64d",x);
        #else
        #ifdef __linux
            printf("%lld",x);
        #else
            puts("error:can't recognize the system!");
        #endif
        #endif
    }
    inline void println2(ll x){print2(x);printf("\n");}
    inline void println2(){printf("\n");}
    #undef ll
    #undef OUT_SIZE
    #undef BUF_SIZE
};
using namespace fastIO;
template<typename K, typename I>
struct HollowHeapNode {
    K key;
    I item;

    unsigned id;
    unsigned children;
    unsigned next;
    unsigned second_parent;

    unsigned rank;
    bool hollow;
};

template<typename K, typename I>
class HollowHeap {
private:
    typedef K key_type;
    typedef I item_type;

    unsigned root;

    unsigned* rankmap;
    int rankmap_alloc_size;

    inline void expand_rankmap(unsigned rank) {
        if (rank >= rankmap_alloc_size) {
            rankmap_alloc_size *= 2;
            rankmap = (unsigned*) realloc(rankmap, rankmap_alloc_size * sizeof(unsigned));
            memset(rankmap+rank, 0, rank * sizeof(unsigned));
        }
    }

    unsigned* to_delete;
    int to_delete_index;
    int to_delete_used;
    int to_delete_alloc_size;

    inline void expand_to_delete() {
        if (to_delete_used >= to_delete_alloc_size) {
            to_delete_alloc_size *= 2;
            to_delete = (unsigned*) realloc(to_delete, to_delete_alloc_size * sizeof(unsigned));
        }
    }

    int nodes_used;
    int nodes_alloc_size;
    hh_node* nodes;

    int ranked, eqlinks, links, inserts, decs;

    unsigned link(unsigned u, unsigned v) {
        DEBUG_PRINT("call to link %d(%d) and %d(%d)\n", u, nodes[u].key, v, nodes[v].key);

        links++;
        unsigned parent = u, child = v;
        if (nodes[u].key < nodes[v].key)
            parent = u, child = v;
        else if (nodes[v].key < nodes[u].key)
            parent = v, child = u;
        else {
            eqlinks++;
            if (nodes[u].rank < nodes[v].rank)
                parent = u, child = v;
            else
                parent = v, child = u;
        }

        DEBUG_PRINT("winner: %d(%d)\n", parent, nodes[parent].key);
        nodes[child].next = nodes[parent].children;
        nodes[parent].children = child;
        return parent;
    }

public:
    typedef unsigned reference;

    /**
     * HollowHeap - constructor
     */
    HollowHeap() {
        root = 0;

        rankmap_alloc_size = 16;
        rankmap = (unsigned*) calloc(rankmap_alloc_size, sizeof(unsigned));

        to_delete_alloc_size = 32;
        to_delete = (unsigned*) malloc(to_delete_alloc_size * sizeof(unsigned));

        eqlinks = links = ranked = 0;
        inserts = decs = 0;

        nodes_used = 0;
        nodes_alloc_size = 1024;
        nodes = (hh_node*) malloc(nodes_alloc_size * sizeof(hh_node));
    }

    ~HollowHeap() {
        free(rankmap);
        free(to_delete);
        free(nodes);
    }

    inline hh_node* make_new_node(const key_type& key, const item_type& item) {
        nodes_used++;

        hh_node* result = nodes+nodes_used;
        result->id = nodes_used;
        result->next = result->children = result->second_parent = 0;
        result->rank = 0;
        result->hollow = 0;
        result->key = key;
        result->item = item;

        if (nodes_used+1 >= nodes_alloc_size) {
            nodes_alloc_size *= 2;
            nodes = (hh_node*) realloc(nodes, (nodes_alloc_size) * sizeof(hh_node));
        }

        return nodes+nodes_used;
    }

    /*
     * find_min - returns the minimum element in the heap
     *
     * Returns a pointer to the item corresponding to the minimum key if the
     * number of elements in the heap is at least 1.
     */
    inline item_type* find_min() {
        if (!root)
            return NULL;

        return &((nodes+root)->item);
    }

    /**
     * push - pushes a (key, item) pair into the heap
     *
     * @key:  a key object that is comparable
     * @item: the item itself
     *
     * Returns a pointer to a HollowHeapNode<K, I> that's supposed to serve
     * as a reference handle. This will be required for future operations.
     */
    reference push(const key_type& key, const item_type& item) {
        DEBUG_PRINT("push %d\n", key);
        inserts++;

        // Create a new node and link it to the existing DAG.
        hh_node* new_node = make_new_node(key, item);
        DEBUG_PRINT("new node %p(%d)\n", new_node, key);

        if (!root)
            root = new_node->id;
        else
            root = link(root, nodes_used);

        return nodes_used;
    }

    /**
     * decrease_key - decreases the key on a particular node
     *
     * @u:       a pointer to a HollowHeapNode<K, I>
     * @new_key: the new key value
     *
     * Returns a possibly new pointer to the same item (it may be stored in
     * a different node after the decrease_key operation).
     */
    reference decrease_key(reference u, const key_type& new_key) {
        DEBUG_PRINT("decreasing %d: %d->%d\n", u, nodes[u].key, new_key);
        decs++;

        // If this the given node is already the root node, decreasing the key
        // will not change the heap. Just set the new key and move on.
        if (nodes[u].id == root) {
            DEBUG_PRINT("given node is the root\n");
            nodes[u].key = new_key;
            return u;
        }

        // Otherwise create a new node and move the item.
        make_new_node(new_key, nodes[u].item);

        if (nodes[u].rank > 2)
            nodes[nodes_used].rank = nodes[u].rank - 2;
        else
            nodes[nodes_used].rank = 0;

        nodes[u].hollow = 1;

        // If the original root is the winner, the old node gains a second
        // parent in the form of the new node.
        unsigned old_root = root;
        root = link(root, nodes_used);
        if (root == old_root) {
            nodes[nodes_used].children = nodes[u].id;
            nodes[u].second_parent = nodes_used;
        }

        // Return v so that the caller may update their node table.
        return nodes_used;
    }

    bool empty() {
        return !root;
    }

    void print(unsigned index, int level=0) {
//        if (level == 0)
//            printf("\n");

//        for (int i = 0; i < level-1; i++)
//            printf("|  ");
//        if (level > 0)
//            printf("+--");
        printf("%d\n",nodes[index].key);
		return;
        unsigned next = nodes[index].children;
        if (next == 0)
            return;

        hh_node* child = nodes+next;
        while (child != NULL) {
            next = child->next;

            print(child->id, level+1);

            if (next == 0)
                child = NULL;
            else
                child = nodes+next;
        }
    }

    void print_root() {
        print(root, 0);
    }

    void delete_min() {
        if (!root)
            return;

        int max_rank = -1;

        DEBUG_PRINT("pushing %d(%d) into `to_delete`\n", root, nodes[root].key);
        to_delete_index = 0;
        to_delete_used = 0;
        to_delete[to_delete_used++] = root;
        expand_to_delete();

        while (to_delete_index < to_delete_used) {
            hh_node* parent = nodes+to_delete[to_delete_index];
            DEBUG_PRINT("outer loop: parent = %p(%d)\n", parent, parent->key);

            hh_node* cur = NULL;
            if (parent->children)
                cur = nodes+parent->children;
            DEBUG_PRINT("first child: %p(%d)\n", cur, cur == NULL ? -1 : cur->key);

            hh_node* next;
            while (cur != NULL) {
                next = NULL;
                if (cur->next)
                    next = nodes+cur->next;

                DEBUG_PRINT("[cur=%p(%d)] next=%p(%d)\n", cur, cur->key, next, next == NULL ? -1 : next->key);

                if (cur->hollow == 0) {
                    while (cur->rank < rankmap_alloc_size && rankmap[cur->rank]) {
                        hh_node* other = nodes+rankmap[cur->rank];

                        rankmap[cur->rank] = 0;

                        DEBUG_PRINT("cur=%p(%d) other=%p(%d)\n", cur, cur->key, other, other->key);
                        cur = nodes+link(cur->id, other->id);
                        ranked++;

                        (cur->rank)++;
                    }

                    expand_rankmap(cur->rank);
                    rankmap[cur->rank] = cur->id;

                    if (max_rank < 0 || max_rank < cur->rank)
                        max_rank = cur->rank;
                }
                else {
                    if (!cur->second_parent) {
                        to_delete[to_delete_used++] = cur->id;
                        expand_to_delete();
                    }
                    else {
                        if (cur->second_parent == parent->id) {
                            cur->second_parent = 0;
                            break;
                        }
                        else {
                            cur->second_parent = 0;
                            cur->next = 0;
                        }
                    }
                }

                cur = next;
            }

            to_delete_index++;
        }

        if (max_rank < 0) {
            root = 0;
            return;
        }

        root = rankmap[max_rank];
        rankmap[max_rank] = 0;
        for (int i = max_rank-1; i >= 0; i--) {
            if (rankmap[i]) {
                root = link(root, rankmap[i]);
                rankmap[i] = 0;
            }
        }

        DEBUG_PRINT("%d(%d) is now root\n", root, nodes[root].key);
    }
};
#endif // _HOLLOW_HEAP_H_
HollowHeap<int,int> Hollow_Heap;

int n;
int main() {
	read(n);
	while(n--){
		int flag;
		read(flag);
		if(flag==1){
			int x;
			read(x);
			Hollow_Heap.push(x,1);
		}
		else{
			(flag==2)?Hollow_Heap.print_root():Hollow_Heap.delete_min();
		}
	}
	return 0;
}
原文
存档评论7 条抓取于