Bubble Sort

来源:互联网 发布:java软件培训价格 编辑:程序博客网 时间:2024/05/09 19:21

Bubble Sort

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


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
233 1 231 2 3
 

Sample Output
Case #1: 1 1 2Case #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 3In second case, the array has already in increasing order. So the answer of every number is 0.


冒泡排序中一个数出现的位置的右边界和左边界的值。

考虑一下一个数为什么会向右移动,原因自然是在他右面有比他小的数,因此我们要找到右边比他小的数这就是他最多向右移动的步数(原来的位置+移动的步数就是右边界),然后它会向左移动,一直到自己应该待的位置,所以他的左边界就是min(现在的位置,排好序的位置)。

这里找逆序对要用nLOGn的方法。

#include <cstdio>#include <cmath>#include <cstring>using namespace std;int a[101234];int b[101234];int bit[101234];//int c[101234];int n;int lowbit(int x){    return x&-x;}int que(int x){    int ret=0;    while(x>0)    {        ret+=bit[x];        x-=lowbit(x);    }   return ret;}int add(int x){    while(x<=n)    {        bit[x]++;        x+=lowbit(x);    }}int min(int x, int y){    if(x>y)x=y;    return x;}int abs(int x){    if(x<0)x=-x;    return x;}int main(){    int t, k=1;    scanf("%d", &t);    while(t--)    {        memset(bit, 0, sizeof(bit));        scanf("%d", &n);        int i,sum;        for(i=1; i<=n; i++)        {            scanf("%d", &a[i]);          sum= a[i]-1- que(a[i]-1);            add(a[i]);             b[a[i]]= abs(min(i,a[i])-(i+sum));        }        //for(i=1; i<=n; i++)printf("%d ", c[i]);       // printf("\n");        printf("Case #%d:", k++);        for(i=1; i<=n; i++)        {            printf(" %d", b[i]);                   }        printf("\n");    }    return 0;}



0 0
原创粉丝点击