P1972 [SDOI2009] HH的项链

思路:发现不是一直修改的,所以可以猜到要离线处理。有这个思路,当我们正在维护 1i 区间时,如果这个正在加入的点 i 之前有了,那么把之前加的 1 给去掉,现在的加上 1,然后这个东西我们用树状数组维护,排序 r 就行了。

Code:

// #define FILE_INPUT
#include <bits/stdc++.h>
using namespace std;

bool Mbe;

#define rep(i, a, b) for (int i = a, END##i = b; i <= END##i; i++)
#define per(i, a, b) for (int i = a, END##i = b; i >= END##i; i--)
#define DEBUG(x) cerr << #x << " = " << x << '\n'

using LL = long long;
using ULL = unsigned long long;

inline LL read() {
	LL s = 0, fu = 1; char ch = getchar();
	while (ch < '0' || ch > '9') ch == '-' ? fu = -1 : 0, ch = getchar();
	while (ch >= '0' && ch <= '9') s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar();
	return s * fu;
}

const int Mod = 1e9 + 7;
const int Inf = 0x3f3f3f3f;
const LL InfLL = 0x3f3f3f3f3f3f3f3f;

const int N = 1e6 + 10;
int n, m, a[N], c[N], x[N], y[N], id[N];
int lst[N], ans[N];

#define lowbit(x) ((x) & -(x))
void update(int x, int d) {
	for (; x <= n; x += lowbit(x))
		c[x] += d;
}
int query(int x) {
	int ans = 0;
	for (; x; x -= lowbit(x)) ans += c[x];
	return ans;
}

bool cmp(int a, int b) {
	return y[a] < y[b];
}

void Init() {
}

void Solve() {
	Init();
	n = read();
	rep(i, 1, n) a[i] = read();
	m = read();
	rep(i, 1, m) {
		x[i] = read();
		y[i] = read();
		id[i] = i;
	}
	sort(id + 1, id + m + 1, cmp);
	int cur = 1;
	rep(i, 1, m) {
		int a0 = x[id[i]], b0 = y[id[i]];
		while (cur <= b0) {
			if (lst[a[cur]]) update(lst[a[cur]], -1);
			update(cur, 1);
			lst[a[cur]] = cur;
			cur++;
		}
		ans[id[i]] = query(b0) - query(a0 - 1);
	}
	rep(i, 1, m) printf("%d\n", ans[i]);
}

bool Med;

signed main() {

#ifdef FILE_INPUT
	freopen("input.in", "r", stdin);
#endif

	int T = 1;
//	T = read();
	while (T--) {
		Init();
		Solve();
	}

	cerr << "Memory: " << fixed << setprecision(3) << (&Med - &Mbe) / 1048576.0 << " MB\n";
	cerr << "Time: " << fixed << setprecision(3) << 1e3 * clock() / CLOCKS_PER_SEC << " ms\n";
	return 0;
}
posted @   wh2011  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示