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
  • 相关阅读:
    http
    VUE-1
    AJAX
    html常用标签
    CSS网页布局
    概念整理3
    SEO
    概念整理2
    var
    概念整理
  • 原文地址:https://www.cnblogs.com/chen74123/p/7397514.html
Copyright © 2011-2022 走看看