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

线段树

时间:2016-11-14 09:33:29      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:algo   return   space   cstring   while   stream   blog   sum   nbsp   

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

struct segtree
{
    int left,right,sum;
}tree[10050];
int n,a[5050];

void build(int pos,int l,int r)
{
    tree[pos].left = l;
    tree[pos].right = r;
    tree[pos].sum = 0;
    if(l < r)
    {
        int mid = (l+r)/2;
        build(pos*2,l,mid);
        build(pos*2+1,mid+1,r);
    }
}

int getsum(int pos,int l,int r)
{
    if(tree[pos].left == l && tree[pos].right == r)   return tree[pos].sum;
    int mid = (tree[pos].left+tree[pos].right)/2;
    if(r <= mid)    return getsum(pos*2,l,r);
    if(l > mid)     return getsum(pos*2+1,l,r);
    return getsum(pos*2,l,mid)+getsum(pos*2+1,mid+1,r);
}

void update(int pos,int num)
{
    tree[pos].sum++;
    if(tree[pos].left == tree[pos].right)   return;
    int mid = (tree[pos].left+tree[pos].right)/2;
    if(num <= mid)  update(pos*2,num);
    else    update(pos*2+1,num);
}

int main()
{
    while(~scanf("%d",&n))
    {
        int ans = 0;
        build(1,0,n-1);
        for(int i = 0;i < n;i++)
        {
            scanf("%d",&a[i]);
            ans += getsum(1,a[i],n-1);
            update(1,a[i]);
        }
        int temp = ans;
        for(int i = 0;i < n-1;i++)
        {
            temp += n-1-a[i]-a[i];
            ans = min(temp,ans);
        }
        printf("%d\n",ans);
    }
    return 0;
}

//HDU1394

 

线段树

标签:algo   return   space   cstring   while   stream   blog   sum   nbsp   

原文地址:http://www.cnblogs.com/zhurb/p/6060592.html

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