题目链接: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
原文地址:http://blog.csdn.net/mullerwch/article/details/38383229