题目链接:[CodeForces264A]Escape from Stones[dfs][two pointers]
题意分析:初始主角站在区间[0,1]的中点,然后有大量石头掉落(每次都会掉落在当前区间中点),此时主角会向左右移动,每次移动后的区间缩小为1/2。要求:从左往右输出出现的石头编号。
解题思路:一、可以在脑袋里面模拟一下过程,最好画个图,然后就可以用一个指针代表头指针,一个代表尾部指针,每次在出现左右选择时,赋予编号。二、dfs搜索,感觉特别赞~思路就是按照dfs递归的本质,当向左时,此时的石头一定是比今后的距离都远的,向右时,此时石头一定是比今后的距离都小的。
个人感受:自己第一反应这题是暴力。结果精度上被卡。试着想到并查集啊什么的,无果。然后发现这两种都不错,特别是dfs感觉特赞~
具体代码如下:
=============DFS君========================
#include <iostream>
#include <cstdio>
#include <string>
typedef long long ll;
using namespace std;
string s;
void dfs(int x)
{
if (s[x] == 0) return;
if (s[x] == 'l')
{
dfs(x + 1);
printf("%d\n", x + 1);
}
else
{
printf("%d\n", x + 1);
dfs(x + 1);
}
}
int main() {
cin >> s;
dfs(0);
return 0;
}
=============two pointers君========================
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 1e6 + 11;
char s[MAXN];
int main()
{
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;
}