题目:
Description
The polar bears are going fishing. They plan to sail from (sx, sy) to (ex, ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y).
- If the wind blows to the east, the boat will move to (x + 1, y).
- If the wind blows to the south, the boat will move to (x, y - 1).
- If the wind blows to the west, the boat will move to (x - 1, y).
- If the wind blows to the north, the boat will move to (x, y + 1).
Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x, y). Given the wind direction for t seconds, what is the earliest time they sail to (ex, ey)?
Input
The first line contains five integers t, sx, sy, ex, ey(1 ≤ t ≤ 105, - 109 ≤ sx, sy, ex, ey ≤ 109). The starting location and the ending location will be different.
The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: "E" (east), "S" (south), "W" (west) and "N" (north).
Output
If they can reach (ex, ey) within t seconds, print the earliest time they can achieve it. Otherwise, print "-1" (without quotes).
Sample Input
5 0 0 1 1 SESNW
4
10 5 3 3 6 NENSWESNEE
-1
#include <stdio.h>
#include <string.h>
#define MAX 100010
char str[MAX];
int main()
{
int t, sx, sy, ex, ey, e, s, w, n, i, tag, nx, ny;
while(~scanf("%d%d%d%d%d", &t, &sx, &sy, &ex, &ey))
{
getchar();
tag = e = w = s = n = 0;
memset(str, 0, sizeof(str));
gets(str);
nx = sx - ex;
ny = sy - ey;
for(i = 0; i < t; i++)
{
switch(str[i])
{
case 'E': e++; break;
case 'W': w++; break;
case 'S': s++; break;
case 'N': n++; break;
}
}
if( ((sx < ex) && (sx + e < ex)) || ((sx > ex) && (sx - w > ex)) ||
((sy < ey) && (sy + n < ey)) || ((sy > ey) && (sy - s > ey)) )
{
puts("-1");
continue;
}
if((sx == ex) || (sy == ey)) tag++;
for(i = 0; i < t; i++)
{
if(2 == tag) break;
if((sx < ex) && e) { if('E' == str[i]) {nx++; if(0 == nx) tag++; continue;} }
if((sx > ex) && w) { if('W' == str[i]) {nx--; if(0 == nx) tag++; continue;} }
if((sy < ey) && n) { if('N' == str[i]) {ny++; if(0 == ny) tag++; continue;} }
if((sy > ey) && s) { if('S' == str[i]) {ny--; if(0 == ny) tag++; continue;} }
}
if(2 == tag) printf("%d\n", i);
}
return 0;
}
总结;
这是一道水题。但是我却wa了好几次。。。,想了一下,wa是因为之前有些东西没有考虑到,比如,sx==ex或是sy==ey,还有一点,就是在计算最短时间时,我用来计数的是原有的s、n、e、x,而不是所需的次数nx、ny,这个应该是因为有点逻辑混乱了。继续加油!!!
本文介绍了一道关于极地熊利用风力航行的算法题。任务是在给定时间内找到从起点到终点的最早到达时间,通过分析风向变化和锚定策略,给出了一种实现方法,并附带源代码及解析。
1万+

被折叠的 条评论
为什么被折叠?



