zoukankan      html  css  js  c++  java
  • P3919 (模板)可持久化数组 (主席树)

    题目链接


    Solution

    主席树水题,连差分的部分都不需要用到.
    直接用主席树的结构去存一下就好了.

    Code

    #include<bits/stdc++.h>
    #define mid (l+r)/2
    using namespace std;
    const int maxn=2000008;
    int T[maxn],tot,n,m;
    int ch[maxn*10][2];
    int a[maxn],id[maxn];
    int	w[maxn*10],num;
    
    int read()
    {
    	char ch=getchar(); int f=1,w=0;
    	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    	while(ch<='9'&&ch>='0'){w=w*10+ch-'0';ch=getchar();}
    	return f*w;
    }
    
    void build(int &node,int l,int r)
    {
    	node=++tot;
    	if(l==r)
    	{w[node]=a[l];return;}
    	build(ch[node][0],l,mid);
    	build(ch[node][1],mid+1,r);
    	return;
    }
    
    void update(int &node,int pre,int l,int r,int x,int v)
    {
    	node=++tot;
    	if(l==r){w[node]=v;return;}
    	ch[node][0]=ch[pre][0];
    	ch[node][1]=ch[pre][1];
    	if(x>mid) update(ch[node][1],ch[pre][1],(mid)+1,r,x,v);
    	else update(ch[node][0],ch[pre][0],l,mid,x,v);
    }
    
    int query(int node,int l,int r,int x)
    {
    	if(l==r)return w[node];
    	if(x>mid)return query(ch[node][1],(mid)+1,r,x);
    	else return query(ch[node][0],l,mid,x);	
    }
    
    int main()
    {
    	//freopen("a.in","r",stdin);
    	//freopen("a.out","w",stdout);
    	cin>>n>>m;
    	for(int i=1;i<=n;i++)	
    	a[i]=read();
    	build(T[0],1,n);
    	for(int i=1;i<=m;i++)
    	{
    		int opt,pre,x,v;
    		pre=read(); opt=read(); x=read();
    		if(opt==1)
    		v=read(),num++,
    			update(T[num],T[id[pre]],1,n,x,v),id[i]=num;
    		else
    			printf("%d
    ",query(T[id[pre]],1,n,x)),
    			id[i]=id[pre];
    	}
    }
    
    
    
  • 相关阅读:
    代码质量检查那点事
    DataTable中如何去除重复的项【转】
    TAG的用法和用途[转]
    Sqlite: unable to open database file
    [转]DataGridView绑定泛型List的种种
    SQLite清空表并将自增列归零[转]
    .NET特性-Attribute
    基于边信道的硬件攻击小综述
    国内下载vscode速度慢解决
    centos与内核版本对应关系
  • 原文地址:https://www.cnblogs.com/Kv-Stalin/p/9383536.html
Copyright © 2011-2022 走看看