POJ 1990 MooFest(树状数组)


http://poj.org/problem?id=1990


题意:一群奶牛排在一根坐标轴上,并且知道奶牛的位置,每个奶牛都有一个对话时候能够听到的最小音量。每两个奶牛对话的时候,所需要的音量就是两头牛最小音量的较大值,消耗体力就是这个较大值乘两头奶牛的距离。问两两奶牛都进行对话的情况下,要消耗多少体力?


输入数据中,左边的数代表音量,右边代表位置。将奶牛按照音量从小到大排序,那么可以保证,每一头奶牛在和排在它前面的牛交谈的时候,用的是自己的音量。接下来可以发现,以样例为例子,排序后变为

2 5

2 6

3 1

4 3

那么消耗体力值可以表示为2*(6-5)+3*(6-1+5-1)+4*(3-1+6-3+5-3),观察括号中的数可以发现,必须知道对于当前这头牛,它前面位置比它小的牛数量num_less和位置值总和site_less,再根据它前面的牛位置值总和site_tot,牛的总数num_tot,求出num_more和site_more。




#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define N 20005
#define VN 20001
#define LL __int64
using namespace std;
LL n, site_tot, site_less, site_more, num_tot, num_less, num_more, c1[N], c2[N];
LL ans;
struct Node{
LL v;
LL s;
}cow[N];
bool cmp(Node a, Node b)
{
    return a.v < b.v;
}
LL lowbit(LL x)
{
    return x & (-x);
}
LL query(LL *c, LL x)
{
    int sum = 0;
    while (x > 0)
    {
        sum += c[x];
        x -= lowbit(x);
    }
    return sum;
}
void add(LL *c, LL i, LL x)
{
    while (i <= VN)
    {
        c[i] += x;
        i += lowbit(i);
    }
}
int main()
{
    while (~scanf("%d", &n))
    {
        for (int i = 1; i <= n; i++)
            scanf("%d%d", &cow[i].v, &cow[i].s);
        sort(cow+1, cow+n+1, cmp);
        site_tot = 0;
        ans = 0;
        memset(c1, 0, sizeof(c1));
        memset(c2, 0, sizeof(c2));
        for (int i = 1; i <= n; i++)
        {
            site_less = query(c1, cow[i].s-1);
            site_more = site_tot - site_less;
            num_tot = i - 1;
            num_less = query(c2, cow[i].s-1);
            num_more = num_tot - num_less;
            ans += cow[i].v * (num_less * cow[i].s - site_less + site_more - num_more * cow[i].s);
            site_tot += cow[i].s;
            add(c1, cow[i].s, cow[i].s);
            add(c2, cow[i].s, 1);
        }
        printf("%I64d\n", ans);
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值