Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.
The stones always fall to the center of Liss's interval. When Liss occupies the interval [k - d, k + d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k - d, k]. If she escapes to the right, her new interval will be [k, k + d].
You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls.
The input consists of only one line. The only line contains the string s (1 ≤ |s| ≤ 106). Each character in s will be either "l" or "r".
Output n lines — on the i-th line you should print the i-th stone's number from the left.
llrlr
3 5 4 2 1
rrlll
1 2 5 4 3
lrlrr
2 4 5 3 1
In the first example, the positions of stones 1, 2, 3, 4, 5 will be
,
respectively. So you should print the sequence: 3, 5, 4, 2, 1.
题目是这样的 在0-1这个区间中 你只能选择向左或向右闪避石头,石头每次砸落到区间的中间。
例如第一题的例子 :llrlr 一开始你处于区间 0-1 石头砸向1/2 然后你先向左闪避 到了0-1/2的地方然后石头砸向1/4,然后你向左闪到了0-1/4,然后石头砸向了1/8地方,你向右闪,到了1/8-1/4的地方,然后石头又砸到了3/16,这个地方 等等 等到全部落下后 第几个落下的石头在从左往右数的第几位上。
解法:
这个就好像一个区间在逐步的进行二分,可以向左分,也可以向右分,但要注意的是 每次都 能确定边界是左边还是右边
例如 1 left 2left 3right 4 left 5right 1 left 确定的是最右边(5的位置) ,2 left 确定的是最靠近1left的左边(4)号位 ,3 right确定的是最左边的(1)号位
往左的石头从最大的开始往下减 往右的石头从左小的开始往上加。
例如llrlr 共5个石头 1l落在5位置 , 2l 落在4位置 , 3r落在1位置, 4l落在3位置 ,5r落在2位置
让后就是个结构体 对位置进行排序输出 落下的石头的序号就好了。
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
char a[2000000];
struct node{
int rank,pos; //rank石头的落下的先后顺序,pos 最后石头从左往右数位于第几位置
} s[1100000];
int cmp(node a,node b) //结构体排序 按位置
{
return a.pos<b.pos;
}
int main()
{
scanf("%s",a);
int len=strlen(a);
int max=len,min=1,i;
for(i=1;i<=len;i++)
{
s[i].rank=i;
if(a[i-1]=='r')s[i].pos=min++; //核心代码 往左的石头从最大的开始往下减 往右的石头从左小的开始往上加。
else s[i].pos=max--;
}
sort(s+1,s+1+len,cmp);
for(i=1;i<=len;i++)
printf("%d\n",s[i].rank);
// scanf("%s",a);
}

本文解析了一道关于石头躲避的编程题,通过模拟石头落在区间并进行左右闪避的过程,最终确定每个石头从左到右的排列顺序。采用结构体记录每个石头的位置,并通过排序输出结果。
331

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



