码迷,mamicode.com
首页 > 编程语言 > 详细

Bubble Sort_树状数组

时间:2016-11-18 06:57:36      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:already   print   using   number   ++i   ring   tin   scan   树状数组   

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.

 

 

【题意】求出每个数能到达的最右和最左的坐标之差

【思路】从最后往前跟新到数组中,并且同时求出有多少个数小于当前数,则他所能到的右坐标是当前位置加上右边小于他的数的个数

左坐标是他min(当前位置,a[i])

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
const int N=100000+10;
int a[N],sum[N*4],pos[N],res[N];
int n;
int lowbit(int p)
{
    return p&(-p);
}
void update(int p)
{
    while(p<=n)
    {
        sum[p]+=1;
        p+=lowbit(p);
    }
}
int get_sum(int p)
{
    int res=0;
    while(p>0)
    {
        res+=sum[p];
        p-=lowbit(p);
    }
    return res;
}
int main()
{
    int t,cas=1;
    scanf("%d",&t);
    while(t--)
    {
        memset(sum,0,sizeof(sum));
        scanf("%d",&n);
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            pos[a[i]]=i;
        }
        for(int i=n; i>0; i--)
    //倒序,从当前位置右边找出有多少小于他的数,记录在res中,他的最大右坐标是res+pos
        {
            update(a[i]);
            res[a[i]]=get_sum(a[i]-1);
        }

        printf("Case #%d: ", cas++);
        for(int i=1; i<=n; i++)
        {
            int minx=min(i,pos[i]);
            if(i!=n) printf("%d ",abs(pos[i]+res[i]-minx));
            else printf("%d\n",abs(pos[i]+res[i]-minx));

        }
    }
    return 0;
}

 

Bubble Sort_树状数组

标签:already   print   using   number   ++i   ring   tin   scan   树状数组   

原文地址:http://www.cnblogs.com/iwantstrong/p/6075974.html

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