码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 2838 Cow Sorting

时间:2017-08-19 20:10:42      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:font   closed   like   esc   ++   inter   gif   details   hang   

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\n",ans);
    return 0;
}
View Code

 

HDU 2838 Cow Sorting

标签:font   closed   like   esc   ++   inter   gif   details   hang   

原文地址:http://www.cnblogs.com/chen74123/p/7397514.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!