也可以在我的洛谷博客↗中食用。
题意
给定若干个长度为 的字符串,其间 R
表示餐厅,D
表示药店,Z
表示两者,.
代表空地。
思路
先是一个 while 循环输入 ,里面定义一个 表示最终答案, 和 分别表示餐厅位置和药店位置,再输入字符串 ,把 的每一个字符遍历一遍。
如果那个字符是 Z
就直接 设为 后退出循环。
R
或者 D
的时候就分别把 或者 赋值为当前循环的次数 。
每次循环时如果 和 已经有值了就把 赋值为 。
注意哦, 初始要赋值为一个较大的值,不然在取最小值的时候会错。
Code
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
int l;
cin >> l;
while(l != 0)
{
int r = -1, d = -1, ans = 1e9;
string s;
cin >> s;
for(int i = 0; i < l; i++)
{
if(s[i] == 'Z')
{
ans = 0;
break;
}
if(s[i] == 'D')
{
d = i;
}
else if(s[i] == 'R')
{
r = i;
}
if(r != -1 && d != -1)
{
ans = min(abs(r - d), ans);
}
}
if(ans == 1e9)//一间都没有
{
ans = 0;
}
cout << ans << "\n";
cin >> l;
}
return 0;
}
如有不严谨之处欢迎指出。
Thanks for reading!