Sail

题目:

N - Sail
Time Limit:1000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u

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

Input
5 0 0 1 1
SESNW
Output
4
Input
10 5 3 3 6
NENSWESNEE
Output
-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,这个应该是因为有点逻辑混乱了。继续加油!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值