zoukankan      html  css  js  c++  java
  • LOJ#3052. 「十二省联考 2019」春节十二响(启发式合并)

    题面

    传送门

    题解

    先考虑一条链的情况,对于(1)号点来说,肯定是左子树中最大值和右子树中最大值一组,左子树中次大值和右子树中次大值一组……以此类推

    那么如果不是一条链呢?我们把所有的链合并起来就是了。每个节点开个堆,启发式合并就可以了

    //minamoto
    #include<bits/stdc++.h>
    #define R register
    #define ll long long
    #define inline __inline__ __attribute__((always_inline))
    #define fp(i,a,b) for(R int i=(a),I=(b)+1;i<I;++i)
    #define fd(i,a,b) for(R int i=(a),I=(b)-1;i>I;--i)
    #define go(u) for(int i=head[u],v=e[i].v;i;i=e[i].nx,v=e[i].v)
    template<class T>inline bool cmax(T&a,const T&b){return a<b?a=b,1:0;}
    template<class T>inline bool cmin(T&a,const T&b){return a>b?a=b,1:0;}
    using namespace std;
    char buf[1<<21],*p1=buf,*p2=buf;
    inline char getc(){return p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++;}
    int read(){
        R int res,f=1;R char ch;
        while((ch=getc())>'9'||ch<'0')(ch=='-')&&(f=-1);
        for(res=ch-'0';(ch=getc())>='0'&&ch<='9';res=res*10+ch-'0');
        return res*f;
    }
    const int N=2e5+5;
    inline int max(R int x,R int y){return x>y?x:y;}
    inline void swap(R int &x,R int &y){R int t=x;x=y,y=t;}
    struct eg{int v,nx;}e[N<<1];int head[N],tot;
    inline void add(R int u,R int v){e[++tot]={v,head[u]},head[u]=tot;}
    priority_queue<int>pool[N],*q[N],*pp=pool;int sz[N],a[N],st[N],top,n;ll res;
    void dfs(int u){
    	q[u]=pp++;
    	go(u){
    		dfs(v);
    		if(sz[v]>sz[u])swap(q[u],q[v]),swap(sz[u],sz[v]);
    		top=0;
    		while(!q[v]->empty()){
    			st[++top]=max(q[u]->top(),q[v]->top());
    			q[u]->pop(),q[v]->pop();
    		}
    		fp(i,1,top)q[u]->push(st[i]);
    	}
    	q[u]->push(a[u]),++sz[u];
    }
    int main(){
    //	freopen("testdata.in","r",stdin);
    	n=read();
    	fp(i,1,n)a[i]=read();
    	for(R int i=2,fa;i<=n;++i)fa=read(),add(fa,i);
    	dfs(1);
    	while(!q[1]->empty())res+=q[1]->top(),q[1]->pop();
    	printf("%lld
    ",res);
    	return 0;
    }
    
  • 相关阅读:
    yum安装LAMP
    CentOS7添加永久静态路由
    批量解压缩,显示进度条(2)
    Django静态文件配置
    大家同乐一下,搞了三天的字符串与STL!终于搞好了。。
    C++动态分配空间
    UNICODE问题
    VC编码规范 (转)
    vs2008中添加splash screen[分享]
    E
  • 原文地址:https://www.cnblogs.com/bztMinamoto/p/10746181.html
Copyright © 2011-2022 走看看