?
代碼來自網上(非原創)
?
?
/*題目地址 ?對于Q操作,求出區間的總和,對于C操作,將區間里的所有數都加上同一個數 ?考慮結點存放兩個信息,一個是該結點區間內的和s,一個是該區間所有數的增量d,對于一個C操作,如果區間剛好等于某結點的區間,則直接將增量加上去,否則,遞歸到左右子結點,并更新父結點的s值。這樣,對于插入與查詢都能達到O(logn)的復雜度. ?Memory:?6760K ?Time:?1579MS ?*/?#include?<iostream> ?using?namespace?std; ?#define?ll?long?long ?const?int?MAXN?=?100001; ?struct?{ ?????int?l,?r; ?????ll?s,?d; ?}?nod[MAXN*3]; ?int?a[MAXN]; ?void?creat(int?t,?int?l,?int?r)?{ ?????if(l?==?r)?{ ?????????nod[t].l?=?nod[t].r?=?l,?nod[t].s?=?a[l],?nod[t].d?=?0; ?????????return; ?????} ?????int?m?=?(l+r)?/?2; ?????nod[t].l?=?l,?nod[t].r?=?r,?nod[t].d?=?0; ?????creat(t*2,?l,?m),?creat(t*2+1,?m+1,?r); ?????nod[t].s?=?nod[t*2].s?+?nod[t*2+1].s; ?} ?void?inc(int?t,?int?l,?int?r,?int?c)?{ ?????if(l?==?nod[t].l?&&?r?==?nod[t].r)?{nod[t].d?+=?c;?return;} ?????if(r?<=?nod[t*2].r)?inc(t*2,?l,?r,?c); ?????else?if(l?>=?nod[t*2+1].l)?inc(t*2+1,?l,?r,?c); ?????else?inc(t*2,?l,?nod[t*2].r,?c),?inc(t*2+1,?nod[t*2+1].l,?r,?c); ?????nod[t].s?=?nod[t*2].s?+?nod[t*2].d?*?(nod[t*2].r-nod[t*2].l+1)?+?nod[t*2+1].s?+?nod[t*2+1].d?*?(nod[t*2+1].r-nod[t*2+1].l+1); ?} ?ll?query(int?t,?int?l,?int?r)?{ ?????if(nod[t].l?==?l?&&?nod[t].r?==?r)?return?nod[t].s?+?nod[t].d?*?(r-l+1); ?????ll?sum; ?????if(r?<=?nod[t*2].r)?sum?=?query(t*2,?l,?r); ?????else?if(l?>=?nod[t*2+1].l)?sum?=?query(t*2+1,?l,?r); ?????else?sum?=?query(t*2,?l,?nod[t*2].r)?+?query(t*2+1,?nod[t*2+1].l,?r); ?????return?sum?+?nod[t].d?*?(r-l+1); ?} ?int?main()?{ ?????int?i,?n,?q,?x1,?x2,?c; ?????char?s[2]; ?????while(scanf("%d%d",?&n,?&q)?!=?EOF)?{ ?????????for(i?=?1;?i?<=?n;?i++)?scanf("%d",?&a[i]); ?????????creat(1,?1,?n); ?????????while(q--)?{ ?????????????scanf("%s%d%d",?s,?&x1,?&x2); ?????????????if(s[0]?==?'C')?{scanf("%d",?&c);?inc(1,?x1,?x2,?c);} ?????????????else?printf("%lld\n",?query(1,?x1,?x2)); ?????????} ?????} ?????return?0; ?}? ?
轉載于:https://blog.51cto.com/wwwacm/846246
總結
以上是生活随笔為你收集整理的PKU A Simple Problem with Integers 3468的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。