P4375 Out of Sorts G
博客内食用效果更佳
题意:求双向冒泡排序的排序次数
对于一个序列, 我们称之为有序的, 当且仅当对于任意一个位置前面没有比它大的数(可以模拟一下)
我们暂且称它为平衡条件吧
首先将序列离散化
相比较于Out of Sorts S, 本题思路在于不动的位置, 结论为对于位置x, ans = max{ans, 前面有几个数的数值大于x}
为什么呢
在x不满足平衡条件的时候
首先第一波操作的时候,对于前x个位置一定会换出一个大于x的数
因为它不满足平衡条件
第二波操作时, 又会有一个小于等于x的数插回来
因为回来的时候一定会冒泡出一个位置在x后的最小值, 因为x不满足平衡条件, 所以最小值小于等于x, 就又插了回来
有人可能会问为什么Out of Sorts S不能用这个式子嘞, 因为每次换出的一定大于x, 但x+1位置上的数可能换过来, 而它有可能大于x
由此可知, 求每个位置前大于其的数就行啦
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 100500;
int d[N], n;
int read(void) {
int x = 0;
char c = getchar();
while (!isdigit(c)) c = getchar();
while (isdigit(c)){
x = (x << 3) + (x << 1) + c - '0';
c = getchar();
}
return x;
}
struct node{
int val, pos;
bool operator < (const node &i) const{
if (val == i.val) return pos < i.pos;
return val < i.val;
}
}p[N];
inline int low(int x) {
return x & -x;
}
int get(int x) {
int tmp = 0;
for (;x;x -= low(x)) tmp += d[x];
return tmp;
}
void add(int x) {
for (;x <= n; x += low(x)) d[x]++;
}
bool cmp(node i,node j) {
return i.pos < j.pos;
}
int main() {
n = read();
for (int i = 1;i <= n; i++) p[i] = (node){read(),i};
sort(p + 1,p + n + 1);
for (int i = 1;i <= n; i++) p[i].val = i;
sort(p + 1,p + n + 1, cmp);
int ans = 1;
for (int i = 1;i <= n; i++) {
add(p[i].val);
ans = max(ans, i - get(i));
}
printf ("%d\n", ans);
return 0;
}
/*
6
2 5 6 3 1 4
*/