码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1556 Color the ball

时间:2014-08-05 14:12:29      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:数学   树状数组   hdu   

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1556


解析:

1.如果进行每一个计数的话,容易TLE(超时)。

2.一种数学的编码思路:

/*
ID:muller8
Name: 1556 Color the ball
Reference:
*/

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
#define MAXN 100005
#define INF 1e9

int a[MAXN];

int main(){
    int N;
    while(~scanf("%d", &N),N){
        fill(a+1, a+N+1, 0);
        int m, n;
        int i, k = 0;
        for(i=0; i<N; ++i){
            scanf("%d%d", &m, &n);
            a[m]++;
            a[n+1]--;
        }
        for(i=1; i<N; ++i){
            k += a[i];
            printf("%d ", k);
        }
        printf("%d\n", k+a[N]);
    }
    return 0;
}

3.可以用树状数组解决

基本知识:http://blog.csdn.net/mullerwch/article/details/38382831

/*
ID:muller8
Name: 1556 Color the ball
Reference:树状数组
*/

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
#define MAXN 100000
#define INF 1e9

int c[MAXN+10];
int ans[MAXN+10];
int N;
int lowbit(int n){
    return n&(n^(n-1));
}

void ADD(int p, int val){
    while(p<=N){
        c[p] += val;
        p += lowbit(p);
    }
}

int getsum(int p){
    int sum = 0;
    while(p>0){
        sum += c[p];
        p -= lowbit(p);
    }
    return sum;
}

int main(){
    while(~scanf("%d", &N),N){
        int a, b;
        int i,j;
        fill(c+1, c+N+1, 0);
        for(i=0; i<N; ++i){
            scanf("%d%d", &a, &b);
            ADD(a, 1);
            ADD(b+1, -1);
        }
        printf("%d", getsum(1));
        for(i=2; i<=N; ++i){
            printf(" %d",getsum(i));
        }
        printf("\n");
    }
    return 0;
}


HDU 1556 Color the ball,布布扣,bubuko.com

HDU 1556 Color the ball

标签:数学   树状数组   hdu   

原文地址:http://blog.csdn.net/mullerwch/article/details/38383229

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!