codeforces 1000F One Occurrence(线段树、想法)

codeforces 1000F One Occurrence

题意

多次询问lr之间只出现过一次的数是多少。

题解

将查询按照左端点排序,对于所有值维护它在当前位置后面第二次出现是什么时候,那么查询区间最大值即可。

代码

#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define rep(i, a, b) for(int i=(a); i<(b); i++)
#define sz(a) (int)a.size()
#define de(a) cout << #a << " = " << a << endl
#define dd(a) cout << #a << " = " << a << " "
#define all(a) a.begin(), a.end()
#define endl "\n"
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
//---

const int N = 500050;

int n, m;
int a[N], ans[N], nx[N], vis[N];
bool in[N];
vector<pii> q[N];

struct Seg {
#define ls (rt<<1)
#define rs (ls|1)
	static const int N = ::N*4+22;
	int ma[N], ind[N];
	void upd(int p, int c, int l, int r, int rt) {
		if(l == r) {
			ma[rt] = c;
			ind[rt] = l;
			return ;
		}
		int mid = l+r>>1;
		if(p<=mid) upd(p, c, l, mid, ls);
		else upd(p, c, mid+1, r, rs);
		ma[rt] = max(ma[ls], ma[rs]);
		ind[rt] = ma[ls]>ma[rs] ? ind[ls] : ind[rs];
	}
	void upd(pii &a, pii b) {
		if(a < b) a = b;
	}
	pii qry(int L, int R, int l, int r, int rt) {
		if(L<=l && r<=R) return mp(ma[rt], a[ind[rt]]);
		int mid = l+r>>1;
		pii ans = mp(0, 0);
		if(L<=mid) upd(ans, qry(L, R, l, mid, ls));
		if(R>=mid+1) upd(ans, qry(L, R, mid+1, r, rs));
		return ans;
	}
}seg;

int main() {
	std::ios::sync_with_stdio(false);
	std::cin.tie(0);
	///read
	cin >> n;
	rep(i, 1, n+1) cin >> a[i];
	cin >> m;
	rep(i, 1, m+1) {
		int x, y;
		cin >> x >> y;
		q[x].pb(mp(y, i));
	}
	///solve
	for(int i = n; i; --i) {
		nx[i] = vis[a[i]];
		if(!nx[i]) nx[i] = n+1;
		vis[a[i]] = i;
	}
	memset(vis, 0, sizeof(vis));
	rep(i, 1, n+1) vis[nx[i]] = 1;
	rep(i, 1, n+1) if(!vis[i]) seg.upd(i, nx[i], 1, n, 1);
	rep(i, 1, n+1) {
		for(auto t : q[i]) {
			auto c = seg.qry(i, t.fi, 1, n, 1);
			ans[t.se] = c.fi>t.fi ? c.se : 0;
		}
		if(nx[i]<=n) seg.upd(nx[i], nx[nx[i]], 1, n, 1);
	}
	rep(i, 1, m+1) cout << ans[i] << endl;
	return 0;
}
posted @ 2018-06-28 20:09  yuanyuan-97  阅读(358)  评论(0编辑  收藏  举报