NYOJ-522 Interval【樹狀數組】

來源:互聯網
上載者:User

題目連結:http://acm.nyist.net/JudgeOnline/problem.php?pid=522

題目大意:

給你M個區間,區間內所有整數個數+1,然後給出N個詢問,問k這個數字在所有區間中一共出現了幾次

解題思路:

當時第一思路就是裸的插線問點嘛,但是當時想著可能是水題,乾脆水過去算了。但是悲劇了。。

於是用樹狀數組搞,結果悲劇的把WA看成TLE,以為看錯題目了?又YY了中方法來寫,總是TLE。最後無意間發現樹狀數組是WA啊。。。激動了一下瞬間知道是0的位置錯了,然後特殊處理了一下就過了。

後來想起來,可以多加1,就不用特殊處理0了。。。。悲劇。

代碼如下:

#include<iostream>#include<cstdio>#include<cstring>#include<string>#include<algorithm>using namespace std;const int N = 100000;const int M = N * 2 + 10;int dp[M];int Scan(){int res = 0 , ch;while( !( ( ch = getchar() ) >= '0' && ch <= '9' ) ){if( ch == EOF )  return 1 << 30 ;}res = ch - '0' ;while( ( ch = getchar() ) >= '0' && ch <= '9' )res = res * 10 + ( ch - '0' ) ;return res ;}int lowbit(int n){return n & (-n);}void add(int i, int plus){while(i > 0){dp[i] += plus;i -= lowbit(i);}}int sum(int n){int sum = 0;while(n <= M){sum +=dp[n];n += lowbit(n);}return sum;}    int main(){int ncase;int num, query;int from, to, now;scanf("%d", &ncase);while(ncase--){int i, j;memset(dp, 0, sizeof(dp));num = Scan(); query = Scan();for(i = 0; i < num; ++i){scanf("%d%d", &from, &to);if(from == -100000){dp[0]++;if(to == from)continue;elsefrom++;}add(from - 1 + N, -1);add(to + N, 1);}for(i = 0; i < query; ++i){scanf("%d", &now);if(now == -100000)printf("%d\n", dp[0]);elseprintf("%d\n", sum(now + N));}}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.