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++.
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.
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.
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 0HintIn 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.
题意:求每个数在冒泡排序的过程中的最右边位置和最左边位置的差是多少。
思路:每个数左边有多少个比它大的数那么这个数会左移多少次,然后a[i]的最终位置是a[i],初始位置是i,左移x次之后的位置是i-x,然后求这三个数之间的最大差就好。当然,求左边比当前数大的数就是求逆序数,用线段树来求很方便。
#include <iostream>
#include<string.h>
#include<vector>
#include<queue>
#include<algorithm>
#include<stdio.h>
#include<math.h>
using namespace std;
typedef long long ll;
int x[100005],node[100005*4],ans[100010];
void update(int pos, int l, int r,int id)
{
if(l == r)
node[pos]++;
else
{
int mid = (l + r) >> 1;
if(id <= mid) update(pos*2, l, mid,id);
else update(pos*2+1, mid+1, r,id);
node[pos] = node[pos*2] + node[pos*2+1];
}
}
int query(int rs,int l,int r,int ll,int rr)
{
if(ll <= l && r <= rr)
return node[rs];
int mid=(l+r)>>1,ans=0;
if(mid>=ll)ans+=query(rs*2,l,mid,ll,rr);
if(mid<rr)ans+=query(rs*2+1,mid+1,r,ll,rr);
return ans;
}
int main()
{
int n,t,o=1;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
memset(node,0,sizeof(node));
memset(ans,0,sizeof(ans));
for(int i=1; i<=n; i++)
{
scanf("%d",&x[i]);
int nx=query(1,1,n,x[i]+1,n);
update(1,1,n,x[i]);
int tem=i-nx;
int max0=max(max(tem,x[i]),i),min0=min(min(tem,x[i]),i);
ans[x[i]]=max0-min0;
}
printf("Case #%d:",o++);
for(int i=1;i<=n;i++)
printf(" %d",ans[i]);
printf("\n");
}
return 0;
}