CF-298B(模拟+找规律)
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 tseconds, what is the earliest time they sail to (ex, ey)?
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).
If they can reach (ex, ey) within t seconds, print the earliest time they can achieve it. Otherwise, print "-1" (without quotes).
5 0 0 1 1
SESNW
4
10 5 3 3 6
NENSWESNEE
-1
In the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.
In the second sample, they cannot sail to the destination.
题意:有个人坐船。要从sx,sy走到ex,ey。这个人靠风来航船。风有四个方向W、E、S、N,给一个字符串s包含这4个方向。字符串的长度代表时间。s[i]代表i分钟的风的方向。每分钟,风能按照方向让这个人走一格。船上有锚,人能够抛锚选择这一分钟不走。问人最快几分钟能到达目的地。如果不能到达目的地,就输出-1。
思路:先看看sx,ex谁大谁小,决定哪个W、E选哪个走。再看sy、ey谁大谁小,决定N、S选哪个走。记录横向应走的步数,和纵向应走的步数。一旦横向和纵向都积累够了相应的步数。就能到达。否则,不能到达。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 int t, x1,x2,y1,y2; 6 char s[100010]; 7 8 int main() 9 { 10 while(~scanf("%d%d%d%d%d", &t, &x1, &y1, &x2, &y2)){ 11 scanf("%s", s); 12 char cx, cy;//横向和纵向选哪个方向走 13 int cntx = 0, cnty = 0;//记录横向和纵向走了几步 14 int cnx, cny;//记录横向和纵向需要走几步才能到达终点 15 16 if(x1 < x2){ 17 cx = 'E'; 18 cnx = x2-x1; 19 } 20 else if(x1 == x2){ 21 cx = '1'; 22 cnx = 0; 23 } 24 else{ 25 cx = 'W'; 26 cnx = x1-x2; 27 } 28 29 if(y1 < y2){ 30 cy = 'N'; 31 cny = y2-y1; 32 } 33 else if(y1 == y2){ 34 cy = '1'; 35 cny = 0; 36 } 37 else{ 38 cy = 'S'; 39 cny = y1-y2; 40 } 41 42 int ans = -2; 43 for (int i = 0; i < strlen(s); i++){ 44 if(s[i] == cx){//风向符合cx方向就走一步 45 cntx++; 46 } 47 if(s[i] == cy){//风向符合cy方向就走一步 48 cnty++; 49 } 50 if(cntx >= cnx && cnty >= cny){//一旦步数积累够了,就跳出 51 ans = i; 52 break; 53 } 54 } 55 56 printf("%d\n", ans+1); 57 } 58 return 0; 59 }

浙公网安备 33010602011771号