CodeForce 264 A. Escape from Stones

January 21, 2013
CodeForces

A. Escape from Stones time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard output

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. Sample test(s) input

llrlr

output

3 5 4 2 1 题目链接http://codeforces.com/contest/264/problem/A

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>

using namespace std;

char s[1000000+10];

int main(void)
{
    //freopen("cf264.in", "r", stdin);
    scanf("%s", s+1);
    int len = strlen(s+1);
    int a[len];
    int left = 1, right = len; 
    for (int i = 1; i <= len; ++i)
    {
        if (s[i] == 'l')
            a[right--] = i;
        else a[left++] = i; 
    }
    for (int i = 1; i <= len; ++i)
        printf("%d\n", a[i]);

    return 0;
}

这道题目不能用暴力做,因为精度不够!看看人家的代码,短小精悍,这题目首先要想明白,抓住问题的关键!

对了,这里有一个小的trick,输入字符串的时候用的scanf(“%s”, s + 1);这样,以后用的时候就可以通过s[k]访问第k个字符了。但是,以后计算字符串长度的时候得用strlen(s+1)……

下面是暴力的代码,直接用数学做……不能过

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <cstring>

using namespace std;
char str[1000000+10];
long double b[1000000+10];
struct stone
{
    long double data;
    int index;
}c[1000000+10];

int cmp(const void *a, const void *b)
{
    return (*(stone*)a).data >  (*(stone*)b).data ? 1 : -1;
}

int main(void)
{
//    freopen("cf264.in", "r", stdin);
    scanf("%s", str);
    b[0] = 0.0;
    b[1] = 0.5;
    for (int i = 0; str[i] != '\0'; ++i)
    {
        if (str[i] == 'l')
            b[i+2] = b[i+1] - (fabs(b[i+1]-b[i]) * 0.5);
        else b[i+2] = b[i+1] + (fabs(b[i+1]-b[i]) * 0.5);
    }
    int len = strlen(str);
    for (int i = 1; i < len + 1; ++i)
    {
        c[i-1].index = i;
        c[i-1].data = b[i];
    }
    qsort(c, len, sizeof(c[0]), cmp);
    for (int i = 0; i < len; ++i)
    {
        printf("%d\n", c[i].index);
    }

    return 0;
}

其中用到了结构体排序。

comments powered by Disqus