Bubble Sort
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2326 Accepted Submission(s): 1134
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
2016 Multi-University Training Contest 4
Recommend
wange2014 | We have carefully selected several similar problems for you: 6361 6360 6359 6358 6357
#include<iostream>
#include<algorithm>
#include<string>
#include<map>//int dx[4]={0,0,-1,1};int dy[4]={-1,1,0,0};
#include<queue>//int gcd(int a,int b){return b?gcd(b,a%b):a;}
#include<vector>
#include<cmath>
#include<stack>
#include<string.h>
#include<stdlib.h>
#include<cstdio>
#define mod 1e9+7
#define ll unsigned long long
#define MAX 1000000000
#define ms memset
#define maxn 200005
using namespace std;
int n,seq[maxn];
/*
题目大意:给定一个初始序列,
对其进行冒泡排序的操作,
计算每个数的最大左右位移偏差。
首先对每个数,
其左移的数量就是左边大于它的数量(找规律),
同理右移的数量就是其右边小于它的数量。
这样树状数组的性质就体现出来了,
对于求解一个数其右边小于它的数的数量,
我们可以逆序扫描数组进行树状数组的更新,
要注意树状数组的答案更新和扫描顺序有很大关系。
如果求出了右边的数量,
根据数学关系可推出左边的关系,详见代码
*/
int tree[maxn];
int lowbit(int x){ return x&(-x); }
int sum(int x)
{
int ret=0;
for(;x>0;ret+=tree[x],x-=lowbit(x));
return ret;
}
void add(int x,int d)
{
for(;x<=n;tree[x]+=d,x+=lowbit(x));
}
int l[maxn],r[maxn],pos[maxn];
int main()
{
int t;scanf("%d",&t);
for(int ca=1;ca<=t;ca++)
{
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&seq[i]);
memset(tree,0,sizeof(tree));
for(int i=n;i>=1;i--)
{
r[seq[i]]=sum(seq[i]);
add(seq[i],1);
pos[seq[i]]=i;///记录位置
l[seq[i]]=r[seq[i]]+pos[seq[i]]-seq[i];///关系
}
printf("Case #%d: ",ca);
for(int i=1;i<=n;i++) printf("%d%c",max(l[i],r[i]),i==n?'\n':' ');
}
return 0;
}