【线段树】 BZOJ 5334

传送门

【题目大意】

有一个初始值为1的变量x。给定一个模数mod。有Q次操作,给x乘上一个数 或 给x除以之前乘的某个数。每次操作完输出x%mod。【x本身并没有取模,只是对答案取模】

【输入】

一共有t组输入(t ≤ 5)

对于每一组输入,第一行是两个数字Q, mod(Q ≤ 100000, mod  ≤ 1000000000); 

接下来Q行,每一行为操作类型op,操作编号或所乘的数字m(保证所有的输入都是合法的).

1 ≤ Q ≤ 100000

【输出】

对于每一个操作,输出一行,包含操作执行后的x%mod的值

Sample Input

1
10 1000000000
1 2
2 1
1 2
1 10
2 3
2 4
1 6
1 7
1 12
2 7

Sample Output

2
1
2
20
10
1
6
42
504
84

【思路】一开始以为是模拟,后来发现之前取了模,就不能直接除回去!

用线段树维护一下就行了。树的叶子节点表示第i次操作的值。修改的时候就是单点修改。每次输出根节点的乘积。

#include<bits/stdc++.h>
#define lc (root<<1)
#define rc (root<<1|1)
#define mid (T[root].l+T[root].r>>1)
#define int long long
using namespace std;
const int maxn=1e6+5;
struct node{
	int l,r,mul;
}T[maxn<<2];
int t,Q,mod,op,m;
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;
}
void prin(int x){
	if(x>9) prin(x/10);
	putchar(x%10+48);
}
inline void pushup(int root) {T[root].mul=(T[lc].mul*T[rc].mul)%mod;}
void build(int root,int l,int r){
	T[root].l=l,T[root].r=r,T[root].mul=1;
	if(l==r) return;
	build(lc,l,mid),build(rc,mid+1,r);
}
void update(int root,int pos,int m){
	if(T[root].l==T[root].r){
		T[root].mul=m;
		return;
	}
	if(pos<=mid) update(lc,pos,m);
	else update(rc,pos,m);
	pushup(root);
}
void delt(int root,int pos){
	if(T[root].l==T[root].r){
		T[root].mul=1;
		return;
	}
	if(pos<=mid) delt(lc,pos);
	else delt(rc,pos);
	pushup(root);
}
signed main(){
	t=read();
	while(t--){
		Q=read(),mod=read();
		build(1,1,Q);
		for(int i=1;i<=Q;++i){
			op=read(),m=read();
			if(op==1){
				update(1,i,m);
				prin(T[1].mul%mod);
				putchar('\n');
			}
			if(op==2){
				delt(1,m);
				prin(T[1].mul%mod);
				putchar('\n');
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/g21wcr/article/details/83349798