HDU 2688

来源:互联网 发布:怎么使用同花顺软件 编辑:程序博客网 时间:2024/05/21 06:43

题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=2688

与树状数组求逆序对的方法类似。

每次R操作在遍历整个区间时更新总对数的值。

特别注意:提交时要用C++。评测时不稳定,该代码有时过不了。

#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>using namespace std;const int maxn=3000010;int n;int a[maxn];int tree[10001];int read(int x){    int tot=0;    while(x){tot+=tree[x];x-=(x&-x);}    return tot;}void add(int num,int x){    while(x<=10000)    {    tree[x]+=num;    x+=(x&-x);}}int main(){    int i,j,m,num,s,t;    char c[4];    __int64 tot;    while(~scanf("%d",&n))    {        memset(tree,0,sizeof(tree));        tot=0;        for(i=1;i<=n;i++)        {            scanf("%d",&a[i]);            if(a[i]!=1)tot+=read(a[i]-1);            add(1,a[i]);        }        scanf("%d",&m);        while(m--)        {            scanf("%s",c);            if(c[0]=='Q')printf("%I64d\n",tot);            if(c[0]=='R')            {                scanf("%d%d",&s,&t);                s++;t++;                if(s>t)swap(s,t);                num=a[s];                for(j=s+1;j<=t;j++)                {                    if(a[j]>num)tot--;                    if(a[j]<num)tot++;                    a[j-1]=a[j];                }                a[t]=num;            }        }    }    return 0;}


原创粉丝点击