清點人數-樹狀數組

來源:互聯網
上載者:User

NK中學組織同學們去五雲山寨參加社會實踐活動,按慣例要乘坐火車去。由於NK中學的學生很多,在火車開之前必須清點好人數

初始時,火車上沒有學生;當同學們開始上火車時,年級主任從第一節車廂出發走到最後一節車廂,每節車廂隨時都有可能有同學上下。年級主任走到第m節車廂時,他想知道第1到m這m節車廂上一共有多少學生,但是他沒有調頭往回走的習慣.也就是說每次當他提問時,m總會比前一次大。

input:
初始時,火車上沒有學生;當同學們開始上火車時,年級主任從第一節車廂出發走到最後一節車廂,每節車廂隨時都有可能有同學上下。年級主任走到第m節車廂時,他想知道第1到m這m節車廂上一共有多少學生,但是他沒有調頭往回走的習慣.也就是說每次當他提問時,m總會比前一次大

output:
有多少個A就輸出多少個數,回答年級主任提出的問題。輸出不要換行!

input:
10 7
A 1
B 1 1
B 3 1
B 4 1
A 2
A 3
A 10

output:
0
1
2
3

【參考程式】://樹狀數組
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
long c[500001];
long
n,k;
long lowbit(long
x)
{
    return x^(x&(x-1
));
}
void modify(long x,long
d)
{
    while (x<=
n)
    {
        c[x]+=d
;
        x+=lowbit
(x);
    }
}
long getsum(long
x)
{
    long s=0
;
    while
(x)
    {
        s+=c[x];
        x-=lowbit
(x);
    }
    return
s;
}
int
main()
{
    scanf("%d%d",&n,&k
);
    getchar();
    memset(c,0,sizeof
(c));
    long
x,y;
    char
c;
    for (int i=1;i<=k;i++
)
    {
        scanf("%c",&c
);

        if (c=='A')
        {
            scanf("%d",&x
);
            getchar();
            printf("%d",getsum
(x));
        }
        else if (c=='B'
)
        {
            scanf("%d%d",&x,&y
);
            getchar();
            modify(x,y);
        }
        else
        {
            scanf("%d%d",&x,&y
);
            getchar();
            modify(x,-y
);
        }
    }
    system("pause"
);
    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.