zoukankan      html  css  js  c++  java
  • 曼哈顿树

    #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('
    ');
        }
        return 0;
    }
  • 相关阅读:
    Python必须知道的异常处理
    类的内置方法(用实际代码来验证)
    类的三大特性(继承, 封装, 多态)
    面向对象编程代码详解(依赖关系,关联关系,组合关系)
    函数(匿名函数,嵌套函数,高阶函数,装饰器)
    常用模块
    对磁盘文件的操作(文件处理)
    字符编码
    常用数据类型
    编程介绍
  • 原文地址:https://www.cnblogs.com/war1111/p/13214970.html
Copyright © 2011-2022 走看看