P4378 [USACO18OPEN]Out of Sorts S

定义$f(n)$ 为 **每个点前面的序列与其组成的逆序对的数量**, 那么答案肯定是$max(f(n))$. 毕竟,冒泡排序一次只能推一个数到它后面嘛. 别忘了最后判断排序成功的时候也算一次, 答案要 + 1. 方法我想的是离散化 + 线段树, 比别人的纯贪心做法不知道差到哪儿去了qwq
#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 1e5 + 20;
inline int read()
{
	int x = 0; char ch = getchar();
	while(!isdigit(ch)) ch = getchar();
	while(isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
	return x;
}

int N;
int a[MAXN];

namespace stree
{
	#define mid ((l + r) >> 1)
	#define ls (o << 1)
	#define rs ((o << 1) | 1)

	int node[MAXN << 2];

	inline void pushup(int o){
		node[o] = node[ls] + node[rs];
	}

	void modify(int o, int l, int r, int p, int v){
		if(l == r) return node[o] += v, void();
		if(p <= mid) modify(ls, l, mid, p, v);
		else modify(rs, mid + 1, r, p, v);
		return pushup(o);
	}

	int query(int o, int l, int r, int a, int b){
		if(l > b || r < a || l > r) return 0;
		if(a <= l && r <= b) return node[o];
		else return query(ls, l, mid, a, b) + query(rs, mid + 1, r, a, b);
	}
}

vector<int> cp;
void compress(){
	for(int i = 1; i <= N; i++) cp.push_back(a[i]);
	sort(cp.begin(), cp.end());
	cp.erase(unique(cp.begin(), cp.end()), cp.end());
}

int main()
{
	cin>>N;
	for(int i = 1; i <= N; i++) a[i] = read();
	compress();
	int ans = 0;
	for(int i = 1; i <= N; i++){
		int tmp = upper_bound(cp.begin(), cp.end(), a[i]) - cp.begin();
		ans = max(ans, stree::query(1, 1, N, tmp + 1, cp.size()));
		stree::modify(1, 1, N, tmp, 1);
	}
	cout<<ans + 1<<endl;
	return 0;
}
posted @ 2018-08-11 09:51  俺是小程  阅读(233)  评论(0编辑  收藏  举报