题目描述:
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的序列模拟冒泡排序的过程,计算其每个位置的最左位置和最右位置的差。
这题当时推了很久。我推导的公式是原序列每个数,后面比这个数小的数个数和前面比这个数大的数个数的最大值。
这题用树状数组做的。所以我推了半天不会用树状数组也是白扯。尴尬。
但是证明我推导的公式是对的。
代码如下:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=100005;
int a[maxn];
int b[maxn];
int c[maxn];
int d[maxn];
int x[maxn];
int y[maxn];
int ans1[maxn];
int ans2[maxn];
int lowbit(int t)
{
return t&-t;
}
void update1(int x)
{
while(x<maxn)
{
a[x]++;
x+=lowbit(x);
}
}
void update2(int x)
{
while(x)
{
c[x]++;
x-=lowbit(x);
}
}
int sum1(int x)
{
int sum=0;
while(x)
{
sum+=a[x];
x-=lowbit(x);
}
return sum;
}
int sum2(int x)
{
int sum=0;
while(x<maxn)
{
sum+=c[x];
x+=lowbit(x);
}
return sum;
}
int main()
{
int t;
scanf("%d",&t);
int n;
for(int k=1;k<=t;k++)
{
memset(a,0,sizeof(a));
memset(c,0,sizeof(c));
memset(ans1,0,sizeof(ans1));
memset(ans2,0,sizeof(ans2));
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&y[i]);
x[n-i+1]=y[i];
}
for(int i=1;i<=n;i++)
{
ans1[n-i+1]=sum1(x[i]);//后面比他小的数的个数
ans2[i]=sum2(y[i]);
update1(x[i]);
update2(y[i]);
}
for(int i=1;i<=n;i++)
{
b[y[i]]=max(ans1[i],ans2[i]);
}
printf("Case #%d:",k);
for(int i=1;i<=n;i++)
printf(" %d",b[i]);
cout<<endl;
}
return 0;
}