题目大意是: Squirrel Liss 住在一个平静的深林, 突然不幸发生了. 山上的石头滚下来了. 然后会有n个石头落下来, Squirrel Liss 将会躲避落石. 石头从1到n依次编号. 落石每次都正好落在Squirrel Liss 居住范围的中间(p-k, p+k). 然后他可以选择向左(p-k, p)或向右(p, p+k).我们将会得到一串由lr组成的字符串来指示他向左或向右.最后从左向右输出石头的编号.
刚开始分析了一下, 发现不就是个双向链表(用数组模拟)插入和输出(O(N)). 样例过了就自信提交. 呵呵time out. (可能常数项大了)
双向链表(time out)
#include<cstdio>
#include<cstring>
using namespace std;
char str[1000001];
int b[1000001];
int f[1000001];
int main()
{
int p = 1, s = 1;
scanf("%s", str);
memset(b, 0, sizeof(b));
memset(f, 0, sizeof(f));
for ( int i = 0; i < strlen(str)-1; i ++ )
{
if ( str[i] == 'l' )
{
if ( f[p] == 0 )
{
b[i+2] = p;
f[p] = i+2;
s = i+2;
}
else
{
int pp;
pp = f[p];
f[i+2] = pp;
b[pp] = i+2;
b[i+2] = p;
f[p] = i+2;
}
}
else
{
if ( b[p] == 0 )
{
f[i+2] = p;
b[p] = i+2;
}
else
{
int pp;
pp = b[p];
b[i+2] = pp;
f[pp] = i+2;
f[i+2] = p;
b[p] = i+2;
}
}
p = i + 2;
}
printf("%d", s);
while ( s = b[s] ) printf("\n%d", s);
return 0;
}
每次向左都会导致下一个石头左移, 所以后落得石头在左边(filo), 每次右移会得到之后的石头位置都在右边. 然后...递归一下...
#include<cstdio>
#include<cstring>
using namespace std;
char str[1000001];
void dfs(int n)
{
if ( str[n] == '\0' ) return;
if ( str[n] == 'l' )
{
dfs(n+1);
printf("%d\n", n+1);
}
else
{
printf("%d\n", n+1);
dfs(n+1);
}
}
int main()
{
scanf("%s", str);
dfs(0);
return 0;
}
其实会发现规律, 顺序输出r, 逆序输出l
#include<cstdio>
#include<cstring>
using namespace std;
char str[1000001];
int ans[1000001];
int main()
{
scanf("%s", str);
int l = 0;
int r = strlen(str) - 1;
for ( int i = 0; i < strlen(str); i ++ )
{
if ( str[i] == 'l' ) ans[r --] = i+1;
else ans[l ++] = i+1;
}
for ( int i = 0; i < strlen(str); i ++ ) printf("%d\n", ans[i]);
return 0;
}