曼哈顿树

#include <bits/stdc++.h>
#define inf 2333333333333333
#define N 1000010
#define p(a) putchar(a)
#define For(i,a,b) for(long long i=a;i<=b;++i)

using namespace std;
long long n,ans,mod=1e9+7;
long long a[N];

struct node{
    long long data;
    node *l;
    node *r;
}*rt;

struct node_comparison {
   bool operator () ( const node* a, const node* b ) const {
    return a->data > b->data;
   }
};

priority_queue<node*,vector<node*>,node_comparison>q;

void in(long long &x){
    long long y=1;char c=getchar();x=0;
    while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
    while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();}
    x*=y;
}
void o(long long x){
    if(x<0){p('-');x=-x;}
    if(x>9)o(x/10);
    p(x%10+'0');
}

void build(){
    while(!q.empty()){
        auto temp=(node*)malloc(sizeof(node));
        auto temp1=q.top();q.pop();
        auto temp2=q.top();q.pop();
        temp->data=temp1->data+temp2->data;
        temp->l=temp1;
        temp->r=temp2;
        if(q.empty()){
            rt=temp;
            break;
        }
        q.push(temp);
    }
}

void dfs(node* now,long long deep){
    if(now==NULL) return;
    if(now->l==NULL && now->r==NULL){
        ans+=deep*now->data;
        ans%=mod;
        return;
    }
    dfs(now->l,deep+1);
    dfs(now->r,deep+1);
}

signed main(){
    while(cin>>n){
        For(i,1,n) in(a[i]);
        rt=(node*)malloc(sizeof(node));
        ans=0;
        For(i,1,n){
            auto temp=(node*)malloc(sizeof(node));
            temp->data=a[i];
            temp->l=NULL;
            temp->r=NULL;
            q.push(temp);
        }
        build();
        dfs(rt,0);
        o(ans);p('\n');
    }
    return 0;
}

 

posted @ 2020-06-30 17:29  WeiAR  阅读(251)  评论(0编辑  收藏  举报