【线段树】【洛谷P3372】【模板】线段树 1(TLE 待补)(懒标记)

 链接:https://www.luogu.org/problemnew/show/P3372

 最后三组数据超时了,应该是需要加上懒标记,刚入门,先留坑,半个月之内补~~~

TLE代码:

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 #define N 100005
 8 #define INF 0x7fffffff
 9 
10 int num[N];
11 struct node 
12 {
13     int l,r;
14     int sum;
15     int mid()
16     {
17         return (l+r)/2;
18     }
19 }tree[N*4];
20 
21 void BuildTree(int root,int l,int r)
22 {
23     tree[root].l = l;
24     tree[root].r = r;
25     if(l == r)
26     {
27         tree[root].sum = num[l];
28         return ;
29     }
30     BuildTree(root*2,l,(l+r)/2);
31     BuildTree(root*2+1,(l+r)/2+1,r);
32     tree[root].sum = tree[root*2].sum+tree[root*2+1].sum;
33 }
34 
35 void add(int root,int i,int t)
36 {
37     tree[root].sum += t;
38     if(tree[root].l == i && tree[root].r == i)
39         return ;
40     if(i <= tree[root].mid())
41         add(root*2,i,t);
42     else
43         add(root*2+1,i,t);
44 }
45 
46 int query(int root,int s,int e)
47 {    
48     if(tree[root].l == s && tree[root].r == e)
49         return tree[root].sum;
50     if(e <= tree[root].mid())
51         return query(root*2,s,e);
52     else
53         if(s > tree[root].mid())
54             return query(root*2+1,s,e);
55         else
56             return query(root*2,s,tree[root].mid())+query(root*2+1,tree[root].mid()+1,e);
57 
58 }
59 
60 int main()
61 {
62     int n,m,i,tmp,x,y,k,j;
63     scanf("%d %d",&n,&m);
64     for(i = 1;i <= n;i++)
65         scanf("%d",&num[i]);
66     BuildTree(1,1,n);
67     for(i = 1;i <= m;i++)
68     {
69         scanf("%d %d %d",&tmp,&x,&y);
70         if(tmp == 1)
71         {
72             scanf("%d",&k);
73             for(j = x;j <= y;j++)
74             {
75                 add(1,j,k);
76             }
77         }
78         else
79         {
80             printf("%d
",query(1,x,y));
81         }
82     }
83 
84     return 0;
85 }
文章搬运自我的个人博客http://duny31030.top 原博客为静态博客,因备份丢失无法继续更新,所以又搬运回博客园,可能部分文章阅读体验不好,可以到我的静态博客搜索相同标题查看
原文地址:https://www.cnblogs.com/duny31030/p/8869954.html