社区讨论

关于memset与build的问题

P4588[TJOI2018] 数学计算参与者 4已保存回复 6

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
6 条
当前快照
1 份
快照标识符
@mhjkzb24
此快照首次捕获于
2025/11/04 04:16
4 个月前
此快照最后确认于
2025/11/04 04:16
4 个月前
查看原帖

Problem

为何使用memset给线段树赋值会导致出现乱码?

memset

CPP
#include<bits/stdc++.h>
using namespace std;
const int MAXN=1e5+2;
int t,mod;
long long w[MAXN*4];
void pushup(int u){
	w[u]=(w[u*2]*w[u*2+1])%mod;
}
bool check1(int l,int r,int L,int R){
	return (L<=l)&&(r<=R);
}
bool check2(int l,int r,int L,int R){
	return (r<L)||(R<l);
}
void update(int u,int l,int r,int x,int k){
	if(check1(l,r,x,x)) w[u]=k;
	else if(!check2(l,r,x,x)){
		int mid=(l+r)/2;
		update(u*2,l,mid,x,k);
		update(u*2+1,mid+1,r,x,k);
		pushup(u);
	}else return ;
}
int main(){
	scanf("%d",&t);
	while(t--){
		int q;
		scanf("%d%d",&q,&mod);
		memset(w,1,sizeof(w));
		for(int i=1;i<=q;i++){
			int op;
			scanf("%d",&op);
			if(op==1){
				int m;
				scanf("%d",&m);
				update(1,1,q,i,m);
			}else{
				int id;
				scanf("%d",&id);
				update(1,1,q,id,1);
			}
			printf("%lld\n",w[1]);
		}
	}
	return 0;
}

输入输出样例

CPP
1
10 1000000000
1 2
2 1
1 2
1 10
2 3
2 4
1 6
1 7
1 12
2 7
CPP
886886914
627446273
-682482174
92119060
-808716278
-77836031
-799083002
-78139862
734108664
622351444

build函数

CPP
#include<bits/stdc++.h>
using namespace std;
const int MAXN=1e5+2;
int t,mod;
long long w[MAXN*4];
void pushup(int u){
	w[u]=(w[u*2]*w[u*2+1])%mod;
}
void build(int u,int l,int r){
	if(l==r){
		w[u]=1;
		return ;
	}
	int mid=(l+r)/2;
	build(u*2,l,mid);
	build(u*2+1,mid+1,r);
	pushup(u);
	return ;
}
bool check1(int l,int r,int L,int R){
	return (L<=l)&&(r<=R);
}
bool check2(int l,int r,int L,int R){
	return (r<L)||(R<l);
}
void update(int u,int l,int r,int x,int k){
	if(check1(l,r,x,x)) w[u]=k;
	else if(!check2(l,r,x,x)){
		int mid=(l+r)/2;
		update(u*2,l,mid,x,k);
		update(u*2+1,mid+1,r,x,k);
		pushup(u);
	}else return ;
}
int main(){
	scanf("%d",&t);
	while(t--){
		int q;
		scanf("%d%d",&q,&mod);
		//memset(w,1,sizeof(w));
		build(1,1,q);
		for(int i=1;i<=q;i++){
			int op;
			scanf("%d",&op);
			if(op==1){
				int m;
				scanf("%d",&m);
				update(1,1,q,i,m);
			}else{
				int id;
				scanf("%d",&id);
				update(1,1,q,id,1);
			}
			printf("%lld\n",w[1]);
		}
	}
	return 0;
}

输入输出样例

CPP
1
10 1000000000
1 2
2 1
1 2
1 10
2 3
2 4
1 6
1 7
1 12
2 7
CPP
2
1
2
20
10
1
6
42
504
84

回复

6 条回复,欢迎继续交流。

正在加载回复...