HDU 1556 Color the ball

题目链接: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值