题目大意:
n*m的草地,有些地方是有杂草的,需要你把杂草除掉,并且尽可能地使路径最短。
有以下规则:
- 向你面向的方向移动一个单元格
- 跳到下一行时方向改变(比如你在i行是朝左边,那么到i+1行就朝向右)
数据大小:
1<=n,m<=150
思路:
可以模拟来做,注意到其实每一行的方向是确定的!奇数向右,偶数向左
然后有以下几种情况:
1.当前行和下一行有杂草
2.当前行和下一个有杂草的行之间有奇数个空行
3.当前行和下一个有杂草的行之间有偶数个空行
然后记录最后有杂草的行end,加上每一行所需要的走的最少步数,就是答案。
代码有点绕,慢慢看
#include <iostream>
#include <cstdio>
#include<cstring>
using namespace std;
#define MAX 155
struct Node{
int r,l;
};
int n,m,End,ans,vis;
int main()
{
int x = 0;
Node temp,a;
scanf("%d %d",&n,&m);
for(int i = 1;i <= n;i++)
{
getchar();
int flag = 0;//标注当前行是否有草
char ch;
for(int j = 0;j<m;j++)
{
ch = getchar();
if(ch == 'W')
{
if(flag)
{
a.r = j;
}
else
{
a.l = j;
a.r = j;
}
flag = 1;
End = i-1;//有杂草的最后一行
}
}
if(flag)
{
if(!vis)
{
if(x)//有空行的操作
{
if(x%2)//<--(奇数个空行)
{
ans+=a.r;
}
else//-->(偶数个空行)
{
a.l = 0;
}
}
else//-->
{
ans+=a.l;
}
temp = a;
x = 0;
vis = 1;
}
else
{
if(x == 0 || x%2 == 0)
{
if(i%2)//-->
{
a.l = min(temp.l,a.l);
ans+=temp.r-a.l;
temp = a;
}
else// <--
{
a.r = max(temp.r,a.r);
ans+=a.r-temp.l;
temp = a;
}
}
else if(x%2)
{
if(i%2)//-->
{
ans+=temp.r-temp.l;
if(temp.r > a.l)
ans+=temp.r-a.l;
else
ans+=a.l-temp.r;
temp = a;
}
else//<--
{
ans+=temp.r-temp.l;
if(temp.l < a.r)
ans+=a.r-temp.l;
else
ans+=temp.l-a.r;
temp = a;
}
}
x = 0;
}
}
else x++;//x记录空行的数量
}
if(vis)
ans+=temp.r-temp.l;
printf("%d",ans+End);
return 0;
}