HDU - 1556 Color the ball

来源:互联网 发布:java遍历json对象 编辑:程序博客网 时间:2024/06/03 08:41

突然发现自己其实并不会使用线段树,决定稍微练一下

1.题面

http://acm.hdu.edu.cn/showproblem.php?pid=1556

2.题意

在一条长为n的线段[1,n],然后有n个操作,每次将[a,b]区间+1,最后输出这条线段上的所有值

3.思路

都说了是水题了,只是来挂一个代码的,有两种写法,线段树和树状数组,zkw版这次不想写。

4.代码

线段树版

/*****************************************************************    > File Name: Cpp_Acm.cpp    > Author: Uncle_Sugar    > Mail: uncle_sugar@qq.com    > Created Time: 2016年05月04日 星期三 14时41分02秒*****************************************************************/# include <cstdio># include <cstring># include <cctype># include <cmath># include <cstdlib># include <climits># include <iostream># include <iomanip># include <set># include <map># include <vector># include <stack># include <queue># include <algorithm>using namespace std;const int debug = 1;const int size  = 100000 + 10; const int INF = INT_MAX>>1;typedef long long ll;struct node{int l,r;int t;}st[3*size];void build(int ll,int rr,int no){st[no].l = ll;st[no].r = rr;st[no].t = 0;if (ll==rr)return;int mid = ll+rr>>1;build(ll,mid,no<<1);build(mid+1,rr,no<<1|1);}void add(int ll,int rr,int no){if (rr<st[no].l||ll>st[no].r)return;else if (ll<=st[no].l&&rr>=st[no].r)st[no].t += 1;else {int mid = (st[no].l + st[no].r)>>1;if (rr<=mid){add(ll,rr,no<<1);}else if (ll>=mid+1){add(ll,rr,no<<1|1);}else {add(ll,rr,no<<1);add(ll,rr,no<<1|1);}}}int ans[size],sz = 0;void Travel(int v,int no){v += st[no].t;if (st[no].l==st[no].r){ans[sz++] = v;}else {Travel(v,no<<1);Travel(v,no<<1|1);}}int main(){std::ios::sync_with_stdio(false);cin.tie(0);int i,j;int n;while (cin >> n){//# cout << "n = " << n << endl;if (n==0)break;build(1,n,1);sz = 0;int a,b;for (i=0;i<n;i++){cin >> a >> b;add(a,b,1);}Travel(0,1);for (i=0;i<n;i++){cout << ans[i] << (i==n-1?'\n':' ');}}return 0;}

树状数组版

/*****************************************************************    > File Name: Cpp_Acm.cpp    > Author: Uncle_Sugar    > Mail: uncle_sugar@qq.com    > Created Time: 2016年05月04日 星期三 15时17分43秒*****************************************************************/# include <cstdio># include <cstring># include <cctype># include <cmath># include <cstdlib># include <climits># include <iostream># include <iomanip># include <set># include <map># include <vector># include <stack># include <queue># include <algorithm>using namespace std;const int debug = 1;const int size  = 100000 + 10; const int INF = INT_MAX>>1;typedef long long ll;int BIT[size];int n;int lowbit(int x){return x&(-x);}void Add(int l,int v){while (l<=n){BIT[l] += v;l += lowbit(l);}}ll Sum(int l){ll sum = 0;while (l>0){sum += BIT[l];l -= lowbit(l);}return sum;}int main(){std::ios::sync_with_stdio(false);cin.tie(0);int i,j;while (cin >> n){if (n==0)break;memset(BIT,0,sizeof(BIT));int a,b;for (i=0;i<n;i++){cin >> a >> b;Add(a,1);Add(b+1,-1);}for (i=1;i<=n;i++){cout << Sum(i) << (i==n?'\n':' ');}}return 0;}



0 0
原创粉丝点击