2019 GUDT WPTC 1 Div2 Problem E(题解) codeforces 115B

原题

题目大意

题目背景是割草,给一个图,然后给出图中草的坐标的,然后要把这些草全部割掉,工作员从图中的(1,1)坐标出发,刚开始面向右边,每次只能进行两个操作 (1)往面向的方向走一格(2)往下走一格并且转向.问工作员把草全部割掉至少走几步?

题目分析

有题可知工作员的行进方向,第一行朝右,第二行朝左,第三行又朝右.因此只要想明白题目还是很好解的,具体过程我会在代码里注释.

代码

 1 #include <cstdio>
 2 #include <cmath>
 3 #include <iostream>
 4 #include <cstring>
 5 #include <algorithm>
 6 #include <vector>
 7 #include <string>
 8 #include <utility>
 9 #include <queue>
10 #include <stack>
11 const int INF=0x3f3f3f3f;
12 using namespace std;
13 
14 char map[200][200];
15 int a[200]; //用来存同一行的草 
16 
17 int main()
18 {
19     int n,m;
20     cin>>n>>m;
21     for(int i=0;i<n;i++)
22     for(int j=0;j<m;j++)
23     cin>>map[i][j];
24     int k=0,temp=0,ans=0,vir=0; //k是行数,temp是记录起始位置,vir用来记录往下走了多少格 
25     while(k!=n)
26     {
27         int cnt=0; //cnt用来记录同一行的草的数量 
28         if(k&1) //奇数行工作员向左(k从0开始) 
29         {
30             for(int i=m-1;i>=0;i--)
31             if(map[k][i]=='W') a[cnt++]=i;
32             if(cnt) //这一行有草
33             { 
34                 //a[0]是该行最右边的草,a[cnt-1]是该行最左边的草 
35                 if(a[0]>temp) ans=ans+a[0]-temp+a[0]-a[cnt-1];
36                 else ans=ans+temp-a[cnt-1];
37                 vir=k;
38             }
39         }
40         else
41         {
42             for(int i=0;i<m;i++)
43             if(map[k][i]=='W') a[cnt++]=i;
44             
45             if(cnt)
46             {
47                 //a[cnt-1]是该行最右边的草,a[0]是该行最左边的草 
48                 if(a[0]<temp) ans=ans+temp-a[0]+a[cnt-1]-a[0];
49                 else ans=ans+a[cnt-1]-temp;
50                 vir=k;
51             }
52         }
53         /* 测试代码可以无视 
54         for(int i=0;i<cnt;i++)
55         printf("a[%d]=%d ",i+1,a[i]);
56         cout<<endl;
57         printf("ans=%d\nvir=%d\n",ans,vir);
58         */
59         if(cnt) temp=a[cnt-1];  //这里注意一下 
60         k++;
61     }       
62     cout<<ans+vir<<endl;       
63     return 0;
64 }

猜你喜欢

转载自www.cnblogs.com/VBEL/p/10440963.html