HDU 1556 Color the ball

来源:互联网 发布:linux系统时钟同步 编辑:程序博客网 时间:2024/05/21 12:50

题目链接:HDU 1556 Color the ball

这个题目可以用树状数组做,也可以用线段树做。

用树状数组的话这里的add函数和sum函数跟之前的写法一样,但是用法不太一样,具体看代码画画图就懂了。

用线段树的话就比较基础了。 

/**765 ms*/#include <iostream>#include <cstring>#include <stdio.h>using namespace std;const int MAX_N = 100000 + 1000;int num[MAX_N];int n;int lowbit(int i){    return i & (-i);}int sum(int i){    int ans = 0;    while(i > 0)    {        ans += num[i];        i -= lowbit(i);    }    return ans;}void add(int i,int val){    while(i <= n)    {        num[i] += val;        i += lowbit(i);    }}int main(){    while(scanf("%d",&n) != EOF,n)    {        memset(num,0,sizeof(num));        for(int i = 0;i < n;i++)        {            int a,b;            scanf("%d %d",&a,&b);            add(a,1);            add(b + 1,-1);        }        for(int i = 1;i < n;i++)            printf("%d ",sum(i));        printf("%d\n",sum(n));    }    return 0;}
#include <iostream>#include <stdio.h>#include <cstring>using namespace std;const int MAX_N = 100000 + 100;struct Node{    int l, r, inc;};Node node[MAX_N << 2];void PushDown(int rt){    if(node[rt].inc)    {        node[rt << 1].inc += node[rt].inc;        node[rt << 1 | 1].inc += node[rt].inc;        node[rt].inc = 0;    }}void build(int l, int r, int rt){    node[rt].l = l;    node[rt].r = r;    node[rt].inc = 0;    if(l == r)        return ;    int mid = (l + r) >> 1;    build(l, mid, rt << 1);    build(mid + 1, r, rt << 1 | 1);}void update(int l, int r, int rt){    if(node[rt].l == l && node[rt].r == r)    {        node[rt].inc += 1;        return ;    }    PushDown(rt);    int mid = (node[rt].l + node[rt].r) >> 1;    if(r <= mid)       update(l, r, rt << 1);    else if(l > mid)        update(l, r, rt << 1 | 1);    else    {        update(l, mid, rt << 1);        update(mid + 1, r, rt << 1 | 1);    }}int get_it(int rt, int k){    if(node[rt].l == k && node[rt].r == k)        return node[rt].inc;    PushDown(rt);    int mid = (node[rt].l + node[rt].r) >> 1;    if(k <= mid)        get_it(rt << 1, k);    else        get_it(rt << 1 | 1, k);}int main(){    int n;    while(scanf("%d", &n), n)    {        build(1, n, 1);        for(int i = 0; i < n; i++)        {            int a, b;            scanf("%d%d", &a, &b);            update(a, b, 1);        }        cout << get_it(1, 1);        for(int i = 2; i < n; i++)            printf(" %d", get_it(1, i));        printf(" %d\n", get_it(1, n));    }    return 0;}


0 0
原创粉丝点击