首页 > 编程语言 > 详细

hdu 5775 Bubble Sort(2016 Multi-University Training Contest 4——树状数组)

时间:2016-07-29 21:29:54      阅读:288      评论:0      收藏:0      [点我收藏+]

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5775

Bubble Sort

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 636    Accepted Submission(s): 378


Problem Description
P is a permutation of the integers from 1 to N(index starting from 1).
Here is the code of Bubble Sort in C++.
for(int i=1;i<=N;++i)
    for(int j=N,t;j>i;—j)
        if(P[j-1] > P[j])
            t=P[j],P[j]=P[j-1],P[j-1]=t;

After the sort, the array is in increasing order. ?? wants to know the absolute values of difference of rightmost place and leftmost place for every number it reached.
 

Input
The first line of the input gives the number of test cases T; T test cases follow.
Each consists of one line with one integer N, followed by another line with a permutation of the integers from 1 to N, inclusive.

limits
T <= 20
1 <= N <= 100000
N is larger than 10000 in only one case. 
 

Output
For each test case output “Case #x: y1 y2 … yN” (without quotes), where x is the test case number (starting from 1), and yi is the difference of rightmost place and leftmost place of number i.
 

Sample Input
2 3 3 1 2 3 1 2 3
 

Sample Output
Case #1: 1 1 2 Case #2: 0 0 0
Hint
In first case, (3, 1, 2) -> (3, 1, 2) -> (1, 3, 2) -> (1, 2, 3) the leftmost place and rightmost place of 1 is 1 and 2, 2 is 2 and 3, 3 is 1 and 3 In second case, the array has already in increasing order. So the answer of every number is 0.
 

Author
FZU
 

Source
 
题目大意:给出一个序列,求对于每一个数字在冒泡排序过程中最大最小下标的差值。

解题思路:

我们从小到大考虑每一个数组,计算出他左边比他小的个数,再用n减去就是右边比他小的数量了,采用树状数组数组的方式来进行运算。


详见代码。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>

using namespace std;

#define N 100000+10
int c[N],a[N],ans[N];

int lowbit(int k)
{
    return k&((k)xor(k-1));
}

void add(int num,int k)
{
    while (k<=N)
    {
        c[k]+=num;
        k+=lowbit(k);
    }
}

int sum(int k)
{
    int s=0;
    while (k)
    {
        s+=c[k];
        k-=lowbit(k);
    }
    return s;
}


int main()
{
    int t,s,Case=1;
    scanf("%d",&t);
    while (t--)
    {
        int n,k,Max,Min;
        scanf("%d",&n);
        memset(c,0,sizeof(c));
        for (int i=1; i<=n; i++)
        {
            k=0;
            scanf("%d",&a[i]);
            add(1,a[i]);//在a[i]的位置加1
            s=a[i]-sum(a[i]);//a[i]后面有多少个比当前数值小的
            Max=max(a[i],i+s);
            Min=min(a[i],i);
            ans[a[i]]=Max-Min;
        }
        printf ("Case #%d:",Case++);
        for (int i=1; i<=n; i++)
            printf (" %d",ans[i]);
        printf ("\n");
    }
    return 0;
}


hdu 5775 Bubble Sort(2016 Multi-University Training Contest 4——树状数组)

原文:http://blog.csdn.net/qiqi_skystar/article/details/52068553

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!