1. 程式人生 > >CodeForces - 264A - Escape from Stones(棧和佇列的應用)

CodeForces - 264A - Escape from Stones(棧和佇列的應用)

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.

Input
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
Output n lines — on the i-th line you should print the i-th stone’s number from the left.

Examples

Input
llrlr
Output
3
5
4
2
1
Input
rrlll
Output
1
2
5
4
3
Input
lrlrr
Output
2
4
5
3
1
Note
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.

題目連結

  • 題意:一隻松鼠要躲避落下的岩石,岩石總是落在松鼠所在的區間。松鼠有兩種選擇,向左‘l’或者向右‘r’, 可以理解為岩石總是落在松鼠所在區間的中間位置,這樣好想一點。然後題目會給你一個字串,裡面代表了松鼠的移動方向,要求你按照從左到右的方向輸出石頭的編號。
  • 題目分析:這個題目找了好多題解,說是要用二分,最後也沒看懂是什麼東西(還是要靠自己),然後我就想要用棧來做。先別急著說我是胡說,我第一感覺真的是用棧。我們這樣想(對了,看下面敘述的過程中建議讀者自己先畫一個圖),當一個石頭落下來,掉落到區間中間,松鼠只有兩個選擇:向左或向右(假設原來區間為[n - k, n + k])
    1、向左,那麼松鼠所在的區間就變成了[n - k, n],也就是右邊已經被石頭擋住了,所以這塊石頭一定是在當前區間的最右邊。那麼按照從左向右的方向,他就要最後輸出了,可是在它之後還有石頭的話,說明這個石頭是先落下,卻要最後被輸出,那麼就是一個入棧操作了。
    2、向右,其實和向左是一樣的分析思路,松鼠的活動區間就變成了[n, n + k],左邊被石頭擋住,那麼以後松鼠的活動範圍被限制在了這個石頭的右邊,也就是說這塊石頭成為了當前區間最左邊的一塊,按照從左往右的順序這個石頭要最先被輸出,那麼其實就是先進先出了那麼就將他存在一個佇列裡面。
    最終會得到一個棧和一個佇列,我們需要先輸出佇列,因為佇列裡面存的是松鼠向右移動的操作,所以裡面的石頭都是位於左面的,不用擔心位置,因為先落下的石頭一定在最左側,棧的也是一樣的道理,所以先輸出佇列裡的元素,然後再輸出棧,就是最終答案了。
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1e6 + 5;
int Stack[maxn], que[maxn];

int main()
{
    char dir;
    int top = 0, tail = 0, cnt = 1;
    while((dir = getchar()) != '\n')
    {
        if(dir == 'l')
            Stack[top++] = cnt++;
        else
            que[tail++] = cnt++;
    }
    for(int i = 0; i < tail; i++)
        printf("%d\n", que[i]);
    while(top != 0)
        printf("%d\n", Stack[--top]);
    return 0;
}