首页 > 其他 > 详细

HDU 2838 Cow Sorting

时间:2017-08-19 19:38:22      阅读:292      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!