Bubble Sort
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 963 Accepted Submission(s): 568
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.
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.
2 3 3 1 2 3 1 2 3
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.
题意:问排序过程中,每个元素到达最左端和最右端位置的差。
思路:查询树状数组。每次加进去一个元素,就差一下他前面有几个,这样就知道之前比他小的有几个,减一下就是后面比他小的,也就是他需要右偏的次数即最右端,最左端可能是他最初的位置也可能是他应该在的位置。
代码:
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <set>
using namespace std;
int P[100000 + 10],ans[100000 + 10];
long long sum[100000 + 10];
long long pm[100000 + 10];
int lowbit(int x)
{
return x&-x;
}
long long premin(int x)
{
long long s = 0;
while(x)
{
s += sum[x];
x -= lowbit(x);
}
return s;
}
int main()
{
int t;
scanf("%d",&t);
int cas = t;
while(t--)
{
int n;
scanf("%d",&n);
memset(sum,0,sizeof sum);
for(int i = 1; i <= n; i++)
{
scanf("%d",&P[i]);
ans[P[i]] = i; //记录每个元素最初的位置
int temp = P[i];
while(temp <= n)
{
sum[temp] += 1;
temp += lowbit(temp); //向后更新
}
pm[P[i]] = premin(P[i]); //算他之前的和即原位置前面比他小的元素的个数
}
printf("Case #%d:",cas-t);
for(int i = 1; i <= n; i++)
printf(" %d",ans[i]+(i-pm[i])-min(ans[i],i));
printf("\n");
}
return 0;
}
430




被折叠的 条评论
为什么被折叠?



