【Luogu】P3939 数颜色

Problem

【Analysis】

对每个颜色开一棵主席树,维护一下和就好了, O ( ( N + M ) l o g N ) O((N + M) log N) O((N+M)logN)

【Code】

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <set>
#include <cstring>
#include <queue>

namespace IO
{
	inline char gc()
    {
        static char s[1<<20|1]={0},*p1=s,*p2=s;
        return (p1==p2)&&(p2=(p1=s)+fread(s,1,1<<20,stdin),p1==p2)?EOF:*(p1++);
    }
//	inline char gc() { return getchar(); }
	inline long long read()
	{
		long long ret=0;bool flag=0;char c=gc();
		while ((c<'0')|(c>'9')) flag ^= !(c^'-'),c=gc();
		while ((c>='0')&(c<='9')) ret=(ret<<1)+(ret<<3)+(c^'0'),c=gc();
		return flag?-ret:ret;
 	}
 	char OutputAns[1<<20|1],*OutputCur = OutputAns;
 	inline void output()
 	{
 		OutputCur -= fwrite(OutputAns,1,OutputCur - OutputAns,stdout);
	}
	inline void print(long long ans)
	{
		char s[20]={0};
		if (OutputCur - OutputAns + sprintf(s,"%lld",ans) >> 20) output();
		OutputCur += sprintf(OutputCur,"%lld",ans);
	}
	inline void printc(char c)
	{
		if (OutputCur - OutputAns + 1 >> 20) output();
		*(OutputCur++) = c;
	}
}

using IO::read;
using IO::print;
using IO::printc;
using IO::output;

const int N = 3e5 + 11;

int tot, n, m, cur;

int Root[N], C[N];

namespace Seg
{
	struct Tree
	{
		int sum, lc : 25, rc : 25;
	} ;
	
	Tree T[N<<5];
	inline int Insert(int now, int l, int r, int pos, int val)
	{
		int mid = l + r >> 1;
		if (!now) now = ++tot;  
		T[now].sum += val;
		if (l == r) return now;
		if (pos <= mid) T[now].lc = Insert(T[now].lc, l, mid, pos, val);
		else T[now].rc = Insert(T[now].rc, mid + 1, r, pos, val);
		return now;
	}
	
	inline int Query(int o, int l, int r, int x, int y)
	{
		if (!o) return 0;
		if (x <= l && y >= r) return T[o].sum;
		int mid = l + r >> 1, res = 0;
		if (x <= mid) res = Query(T[o].lc, l, mid, x, y);
		if (y > mid) res += Query(T[o].rc, mid + 1, r, x, y);
		return res;
	}
}

using Seg::Insert;
using Seg::Query;

inline void Input()
{
	n = read(), m = read();
	for (int i = 1;i <= n; ++i)
	{
		C[i] = read();
		Root[C[i]] = Insert(Root[C[i]], 1, n, i, 1);
	}
}

inline void Solve()
{
	while (m--)
	{
		int opt = read();
		if (opt & 1)
		{
			int l = read(), r = read(), c = read();
			print((long long)Query(Root[c], 1, n, l, r)), printc('\n');
		}
		else
		{
			int num = read();
			Insert(Root[C[num]], 1, n, num, -1);
			Insert(Root[C[num + 1]], 1, n, num + 1, -1);
			Insert(Root[C[num]], 1, n, num + 1, 1);
			Insert(Root[C[num + 1]], 1, n, num, 1);
			std::swap(C[num], C[num + 1]);
		}
	} output();
}

int main(void)
{
	Input();
	Solve();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值