Color the Ball
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3363 Accepted Submission(s): 831
Problem Description
There are infinite balls in a line (numbered 1 2 3 ....), and initially all of them are paint black. Now Jim use a brush paint the balls, every time give two integers a b and follow by a char 'w' or 'b', 'w' denotes the ball from a to b are painted white, 'b'
denotes that be painted black. You are ask to find the longest white ball sequence.
Input
First line is an integer N (<=2000), the times Jim paint, next N line contain a b c, c can be 'w' and 'b'.
There are multiple cases, process to the end of file.
Output
Two integers the left end of the longest white ball sequence and the right end of longest white ball sequence (If more than one output the small number one). All the input are less than 2^31-1. If no such sequence exists, output "Oh, my god".
Sample Input
3
1 4 w
8 11 w
3 5 b
Sample Output
8 11
线段树区间合并。做法和上一篇的POJ 3667 无异。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define SIZE 100005
#define ls l,mid,rt<<1
#define rs mid+1,r,rt<<1|1
using namespace std;
int sum[SIZE<<2],lsum[SIZE<<2],rsum[SIZE<<2],cv[SIZE<<2];
void pushUp(int rt,int itv)
{
lsum[rt] = lsum[rt<<1];
rsum[rt] = rsum[rt<<1|1];
if(lsum[rt] == (itv - (itv >> 1))) lsum[rt] += lsum[rt<<1|1];
if(rsum[rt] == (itv >> 1)) rsum[rt] += rsum[rt<<1];
sum[rt] = max(rsum[rt<<1]+lsum[rt<<1|1],max(sum[rt<<1],sum[rt<<1|1]));
}
void pushDown(int rt,int itv)
{
if(cv[rt] != -1)
{
cv[rt<<1] = cv[rt<<1|1] = cv[rt];
sum[rt<<1] = lsum[rt<<1] = rsum[rt<<1] = cv[rt]? (itv - (itv>>1)):0;
sum[rt<<1|1] = lsum[rt<<1|1] = rsum[rt<<1|1] = cv[rt]? (itv>>1):0;
cv[rt] = -1;
}
}
void build(int l,int r,int rt)
{
sum[rt] = lsum[rt] = rsum[rt] = 0;
cv[rt] = -1;
if(l == r) return;
int mid = (l + r) >> 1;
build(ls);
build(rs);
}
void update(int l,int r,int rt,int L,int R,int w)
{
if(L <= l && r <= R)
{
sum[rt] = lsum[rt] = rsum[rt] = w? (r-l+1):0;
cv[rt] = w;
return;
}
pushDown(rt,r-l+1);
int mid = (l + r) >> 1;
if(L <= mid) update(ls,L,R,w);
if(R > mid) update(rs,L,R,w);
pushUp(rt,r-l+1);
}
int query(int l,int r,int rt,int w)
{
pushDown(rt,r-l+1);
if(l == r) return l;
int mid = (l + r) >> 1;
if(sum[rt<<1] == w) return query(ls,w);
else if(lsum[rt<<1|1] + rsum[rt<<1] == w) return mid-rsum[rt<<1]+1;
return query(rs,w);
}
int N;
int s,e;
char col[5];
int main()
{
//freopen("a.txt","r",stdin);
while(~scanf("%d",&N))
{
build(1,SIZE,1);
while(N --)
{
scanf("%d%d",&s,&e);
scanf("%s",col);
if(col[0] == 'w')
update(1,SIZE,1,s,e,1);
else
update(1,SIZE,1,s,e,0);
}
if(sum[1] == 0)
printf("Oh,my god.\n");
else
{
int lt = query(1,SIZE,1,sum[1]);
printf("%d %d\n",lt,lt+sum[1]-1);
}
}
}
本文介绍了一个基于线段树的数据结构问题——寻找最长白色球序列。通过更新指定区间的颜色并查询最长连续白色球的起始和结束位置来解决。采用递归方式构建、更新线段树,并实现区间合并操作。
6万+

被折叠的 条评论
为什么被折叠?



