Bubble Sort (5775)

时间:2024-01-09 09:45:26

Bubble Sort

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.

题意:

给你一个1到n的排列,然后按照冒泡排序的移动方式,问每个i 能移动到的最左位置和最右位置的差是多少

分析:在冒泡排序过程的变化情况。c会被其后面比c小的数字各交换一次,之后c就会只向前移动。

数组从右向左扫,树状数组维护一下得到每个值左边有多少个比其小的值通过转换得到每个值右边有多

少个比其小的值,加上原位置得到最右位置,最左位置为初始位置和最终位置的最小值。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
const int maxn = ;
int n;
int a[maxn], b[maxn],c[maxn],C[maxn];
void add(int x){
while(x<=n) C[x]++,x+=(x&-x);
//cout<<"x: "<<x<<" C[x]: "<<C[x]<<endl,
} int sum(int x){
int ans=;
while(x>)
ans+=C[x],x-=(x&-x);
//cout<<"ans: "<<ans<<endl;
return ans;
} int main()
{
int t;
int kase = ;
scanf("%d", &t);
while(t--)
{
memset(c, , sizeof(c));
memset(b, , sizeof(b));
int i;
scanf("%d", &n);
for(i=; i<=n; i++ )
{
scanf("%d", &a[i]);
b[a[i]] = i;
}
memset(C,,sizeof(C));
for(int i=;i<=n;i++){
c[i]=sum(a[i]-);
add(a[i]);
// cout<<c[i]<<".."<<endl;
} sort(a+,a+n+);
printf("Case #%d:", ++kase);
for(i = ; i <= n; i++ )
{
int x=i-c[b[i]]-;
printf(" %d", max(abs(b[i]+x-b[i]),abs(b[i]+x-i))); }
printf("\n");
} return ;
}
//自己的绕了点弯路
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=;
int C[maxn],a[maxn],id[maxn],l[maxn],r[maxn],n; void add(int x){
while(x<=n) {
C[x]++,x+=(x&-x);
}
} int sum(int x){
int ans=;
while(x>)
ans+=C[x],x-=(x&-x);
return ans;
} int main(){
int _;
scanf("%d",&_);
for(int case1=;case1<=_;case1++){
scanf("%d",&n);
for(int i=;i<=n;i++)
scanf("%d",&a[i]),l[a[i]]=i;
memset(C,,sizeof(C));
for(int i=n;i>=;i--){
r[a[i]]=i+sum(a[i]-);
add(a[i]);
}
printf("Case #%d: ",case1);
for(int i=;i<=n;i++){
if(i!=n)
printf("%d ",r[i]-min(l[i],i));
else
printf("%d\n",r[i]-min(l[i],i));
}
}
return ;
}
//网上的