import java.io.*; import java.util.*; public class Main { static int N = (int)1e5+10; static long[] arr = new long[N]; static long[] sum = new long[N<<2]; static long[] lazy = new long[N<<2]; static int n, m; public static void pushdown(int o, int l, int r){ if(lazy[o] != 0) { lazy[o*2] += lazy[o]; lazy[o*2+1] += lazy[o]; int mid = (l+r)/2; sum[o*2] += lazy[o] * (mid-l+1); sum[o*2+1] += lazy[o] * (r-mid); //修改tag lazy[o] = 0; } } //构建线段树 public static void build(int o, int l, int r){ if(l == r){ sum[o] = arr[l]; return; } int mid = (l+r)/2; build(o*2, l, mid); build(o*2+1, mid+1, r); maintain(o); } //区间查询 public static long query(int o, int l, int r, int L, int R){ if(L <= l && r <= R){ return sum[o]; } int mid = (l+r)/2; pushdown(o, l, r); long ans = 0l; if(L <= mid){ ans += query(o*2, l, mid, L, R); } if(R>mid){ ans += query(o*2+1, mid+1, r, L, R); } return ans; } //区间修改 public static void add(int o, int l, int r, int L, int R, int val){ if(L <= l && r <= R){ lazy[o] += val; sum[o] += (long)(r-l+1) * val; return; } int mid =l + (r-l)/2; pushdown(o, l, r); if(L <= mid){ add(o*2, l, mid, L, R, val); } if(R>mid){ add(o*2+1, mid+1,r, L, R, val); } maintain(o); } public static void maintain(int o){ sum[o] = sum[o*2] + sum[o*2+1]; } public static void main(String[] args) { FastScanner sc = new FastScanner(); n = sc.nextInt(); m = sc.nextInt(); // 读入数组 for(int i = 1; i <= n; i++){ arr[i] = sc.nextInt(); } // 构建线段树 build(1, 1, n); while(m-- > 0){ int op = sc.nextInt(); if(op == 1){ int l = sc.nextInt(); int r = sc.nextInt(); int val = sc.nextInt(); add(1, 1, n, l, r, val); }else if(op==2){ int a = sc.nextInt(); int b = sc.nextInt(); System.out.println(query(1, 1, n, a, b)); } } } } class FastScanner { static StringTokenizer st; static BufferedReader br; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } long nextLong() { return Long.valueOf(next()); } double nextDouble() { return Double.valueOf(next()); } int nextInt() { return Integer.valueOf(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
标签:lazy,return,int,线段,nextInt,static,sc,new,模板 From: https://www.cnblogs.com/wangruiisboy/p/17925727.html