• HDU 2838 Cow Sorting


    http://acm.hdu.edu.cn/showproblem.php?pid=2838

    Problem Description
    Sherlock's N (1 ≤ N ≤ 100,000) cows are lined up to be milked in the evening. Each cow has a unique "grumpiness" level in the range 1...100,000. Since grumpy cows are more likely to damage Sherlock's milking equipment, Sherlock would like to reorder the cows in line so they are lined up in increasing order of grumpiness. During this process, the places of any two cows (necessarily adjacent) can be interchanged. Since grumpy cows are harder to move, it takes Sherlock a total of X + Y units of time to exchange two cows whose grumpiness levels are X and Y.

    Please help Sherlock calculate the minimal time required to reorder the cows.
     


    Input
    Line 1: A single integer: N
    Lines 2..N + 1: Each line contains a single integer: line i + 1 describes the grumpiness of cow i.
     


    Output
    Line 1: A single line with the minimal time required to reorder the cows in increasing order of grumpiness.
     


    Sample Input
    3 2 3 1
     


    Sample Output
    7
    Hint
    Input Details Three cows are standing in line with respective grumpiness levels 2, 3, and 1. Output Details 2 3 1 : Initial order. 2 1 3 : After interchanging cows with grumpiness 3 and 1 (time=1+3=4). 1 2 3 : After interchanging cows with grumpiness 1 and 2 (time=2+1=3).
     

    思路:

    每个点的代价,就是前面比它大的点的个数乘以这个点再加上前面比它大的点的总和

    然后树状数组乱搞

    #include<bits/stdc++.h>
    using namespace std;
    #define N 100005
    #define ll long long int
    int a[N],cnt[N],n,k,t;
    ll sum[N],ans;
    
    int lowbit(int x)
    {
        return x&(-x);
    }
    
    void add(int x)
    {
        int d=x;
        while(x<=n)
        {
            cnt[x]++;
            sum[x]+=d;
            x+=lowbit(x);
        }
    }
    
    int sum1(int x)
    {
        int s=0;
        while(x)
        {
            s+=cnt[x];
            x-=lowbit(x);
        }
        return s;
    }
    
    ll sum2(int x)
    {
        ll s=0;
        while(x)
        {
            s+=sum[x];
            x-=lowbit(x);
        }
        return s;
    }
    
    int main()
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            add(a[i]);
            t=sum1(a[i]);
            k=i-t;
            if(k!=0)
            {
                ans+=(ll)a[i]*k;
                ans+=sum2(n)-sum2(a[i]);
            }
        }
        printf("%I64d
    ",ans);
        return 0;
    }
    View Code
  • 相关阅读:
    php 将网页执行的输出写入到本地文件中
    网络爬虫技术
    解决:解压zip文件却变成cpgz文件
    SHA1算法实现及详解
    Mac配置PHP开发环境
    项目管理
    Oracle Primavera P6 R84单机版安装教程
    工时
    项目管理软件伙伴https://www.huobanyun.cn/
    Primavera 6.0
  • 原文地址:https://www.cnblogs.com/chen74123/p/7397514.html
Copyright © 2020-2023  润新知