Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

hdu 1394 Minimum Inversion Number 树状数组+递推

$
0
0

水一道,吃饭~

nlogn算出逆序数,再递推得到后面的答案,公式很容易推导。


#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int c[5005];
int a[5005];
int ans,n;
int lowbit(int x)
{
     return x&(-x);
}
int Sum(int end)
{
    int sum=0;
    while(end>0)
    {
         sum+=c[end];
         end=end-lowbit(end);
    }
    return sum;
}
void change(int i,int x)
{
     while(i<=n)
     {
          c[i]=c[i]+x;
          i=i+lowbit(i);
     }
}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        int tmp=0;
        int s;
        for(int i=1;i<=n;i++)
        {
            c[i]=0;
            scanf("%d",&s);
            a[i]=s+1;
        }
        for(int i=1;i<=n;i++)
        {
            change(a[i],1);
            tmp+=(i-Sum(a[i]));
        }
        ans=tmp;
        int now;
        for(int i=1;i<n;i++)
        {
            now=tmp+(n+1-2*a[i]);
            tmp=now;
            ans=min(ans,now);
        }
        printf("%d\n",ans);
    }
    return 0;
}


作者:t1019256391 发表于2013-7-16 11:31:51 原文链接
阅读:0 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>