您的位置:首页 > 其它

HDU 2689 Sort it【树状数组】

2017-07-07 16:47 399 查看

Sort it

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4672 Accepted Submission(s): 3244


[align=left]Problem Description[/align]
You
want to processe a sequence of n distinct integers by swapping two
adjacent sequence elements until the sequence is sorted in ascending
order. Then how many times it need.
For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.

[align=left]Input[/align]
The
input consists of a number of test cases. Each case consists of two
lines: the first line contains a positive integer n (n <= 1000); the
next line contains a permutation of the n integers from 1 to n.

[align=left]Output[/align]
For each case, output the minimum times need to sort it in ascending order on a single line.

[align=left]Sample Input[/align]

3

1 2 3

4

4 3 2 1

[align=left]Sample Output[/align]

0

6

[align=left]Author[/align]
WhereIsHeroFrom

[align=left]Source[/align]
ZJFC 2009-3 Programming Contest

[align=left]Recommend[/align]
[align=left]题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2689[/align]
[align=left]分析:好吧,我智障了,听说有种很快的写法,但好像跑的速度没我快?应该是我代码跑的最快吧,写法也是最复杂的,这题我是用树状数组乱搞的,反正15ms,相当快啊![/align]
[align=left]下面给出AC代码:[/align]

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
inline int read()
{
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
inline void write(int x)
{
if(x<0)
{
putchar('-');
x=-x;
}
if(x>9)
{
write(x/10);
}
putchar(x%10+'0');
}
const int N=1001;
int n;
int num
;
int c
;
struct node
{
int x;
int id;
}q
;
bool cmp(node a,node b)
{
return a.x<b.x;
}
int lowbit(int x)
{
return x&(-x);
}
int getsum(int x)
{
int s=0;
while(x>0)
{
s+=c[x];
x-=lowbit(x);
}
return s;
}
void add(int x,int y)
{
while(x<=n)
{
c[x]+=y;
x+=lowbit(x);
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
memset(c,0,sizeof(c));
memset(num,0,sizeof(num));
for(int i=1;i<=n;i++)
{
scanf("%d",&q[i].x);
q[i].id=i;
}
sort(q+1,q+1+n,cmp);
for(int i=1;i<=n;i++)
{
num[q[i].id]=i;
}
int sum = 0;
for(int i=1;i<=n;i++)
{
add(num[i],1);
sum+=getsum(n)-getsum(num[i]);
}
printf("%d\n",sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: