zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    极速地将git项目部署到SAE的svn服务器上
    深入了解Javascript模块化编程
    自己实现的一款在线Javascript正则表达式测试器——JRE-Parser
    Javascript中的一种深复制实现
    如何循序渐进地学习Javascript
    handsontable实例----来源github
    HandsontableWithVue (一) 导入官方的汉化包
    Handsontable 入坑的开始
    开始前端的生活
    c3p0数据源的第一次尝试
  • 原文地址:https://www.cnblogs.com/chen74123/p/7397514.html
Copyright © 2011-2022 走看看