线段树(单点修改+区间查询)(区间修改+区间查询)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;

public class Main4 {
	
	static int [] a;//原数组
	static int n,q;//数组大小 操作次数
	static long [] tree;
	static long[] tag;
	public static void main(String[] args) {
		n = nextInt();//数组大小
		q = nextInt();//操作次数
		a = new int[(n+1)];//原数组
		for(int i=1;i<=n;i++) a[i] = nextInt();//赋值数组
		tree = new long [4*n];
		tag = new long [4*n];
        build(1,1,n);//初始化线段树
        for(int i=0;i>1;
	    if(L<=mid) res+=query(ls(p),pl,mid,L,R);
	    if(R>mid) res+=query(rs(p),mid+1,pr,L,R);
	    return res;
	}
	private static void update(int p,int pl, int pr,int L,int R, int d) {
		 if(L<=pl&&pr<=R){addtag(p,pl,pr,d);return;}
		    push_down(p,pl,pr);
		    int mid=(pr+pl)>>1;
		    if(L<=mid) update(ls(p),pl,mid,L,R,d);
		    if(R>mid) update(rs(p),mid+1,pr,L,R,d);
		    push_up(p);
	}
	private static void push_down(int p, int pl, int pr) {
		if(tag[p]!=0){
	        int mid=(pl+pr)>>1;
	        addtag(ls(p),pl,mid,tag[p]);
	        addtag(rs(p),mid+1,pr,tag[p]);
	        tag[p]=0;
	    }
	}
	private static void addtag(int p, int pl, int pr, long d) {
		tag[p]+=d;tree[p]+=(pr-pl+1)*d;
	}
	static int ls(int p) {return p<<1;}
	static int rs(int p) {return p<<1|1;}
//	在一段区间上初始化线段树
	private static void build(int p,int pl, int pr) {
		if(pl==pr){
	        tree[p]=a[pl];
	        return ;
	    }
	    int mid=(pl+pr)>>1;
	    build(ls(p),pl,mid);
	    build(rs(p),mid+1,pr);
	    push_up(p);
	}
//	用子节点信息来更新当前节点信息
	private static void push_up(int p) {tree[p]=tree[ls(p)]+tree[rs(p)];}

	static StreamTokenizer streamTokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
	static int nextInt() {
		try {
			streamTokenizer.nextToken();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return (int) streamTokenizer.nval;
		
	}
	
}

你可能感兴趣的:(算法-蓝桥杯,java,jvm,算法)