codeforces 315 B.Sereja and Array

來源:互聯網
上載者:User

地址

B. Sereja and Arraytime limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

Sereja has got an array, consisting of n integers, a1, a2, ..., an.
Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:

  1. Make vi-th array
    element equal to xi.
    In other words, perform the assignment avi = xi.
  2. Increase each array element by yi.
    In other words, perform n assignments ai = ai + yi (1 ≤ i ≤ n).
  3. Take a piece of paper and write out the qi-th
    array element. That is, the element aqi.

給N個元素的數組, 有三種操作 1 是把第i個元素變成v,  2是所有元素都加V, 3 詢問第i個元素的值。

我用了樹狀數組,理論上用線段樹也可以做,但樹狀數組明顯要好寫點,感覺還要比線段樹快些。

樹狀數組原本用來就區間的和,只要稍微改進一下就和更新點,求點的值, 我們如果更新點x為v(當原來點是0事) 我們update(x , v) 和 update(x, -v) , 這樣我們求1到x的和是求到的就是x點的值。

//cf 315 B Sereja and Array//2013-06-13-20.02#include <stdio.h>#include <string.h>const int maxn = 100005;int a[maxn];int n;inline int lowbit(int x){    return x&-x;}int update(int x, int v){    while (x <= n+1)    {        a[x] += v;        x += lowbit(x);    }    return 0;}int getsum(int x){    int sum = 0;    while (x)    {        sum += a[x];        x -= lowbit(x);    }    return sum;}int main(){    int m;    while (scanf("%d %d", &n, &m) != EOF)    {        memset(a, 0, sizeof(a));        int t, op, x, v;        for (int i = 1; i <= n; i++)        {            scanf("%d", &t);            update(i, t);            update(i+1, -t);        }        while (m--)        {            scanf("%d", &op);            if (op == 1)            {                scanf("%d %d", &x, &v);                int tmp = getsum(x);                update(x, -tmp);                update(x+1, tmp);                update(x, v);                update(x+1, -v);            }            else if (op == 2)            {                scanf("%d", &v);                update(1, v);            }            else            {                scanf("%d", &x);                printf("%d\n", getsum(x));            }        }    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.