Fafa and the Gates(模拟)

Posted wkfvawl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Fafa and the Gates(模拟)相关的知识,希望对你有一定的参考价值。

Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.

The world can be represented by the first quadrant of a plane and the wall is built along the identity line (i.e. the line with the equationx = y). Any point below the wall belongs to the first kingdom while any point above the wall belongs to the second kingdom. There is a gate at any integer point on the line (i.e. at points (0, 0), (1, 1), (2, 2), ...). The wall and the gates do not belong to any of the kingdoms.

Fafa is at the gate at position (0, 0) and he wants to walk around in the two kingdoms. He knows the sequence S of moves he will do. This sequence is a string where each character represents a move. The two possible moves Fafa will do are ‘U‘ (move one step up, from (x, y) to (x, y + 1)) and ‘R‘ (move one step right, from (x, y) to (x + 1, y)).

Fafa wants to know the number of silver coins he needs to pay to walk around the two kingdoms following the sequence S. Note that if Fafa visits a gate without moving from one kingdom to another, he pays no silver coins. Also assume that he doesn‘t pay at the gate at point (0, 0), i. e. he is initially on the side he needs.

Description

两个相邻的王国决定在它们之间建造一道隔离墙,墙上有城门,当公民从一个王国走到另一个王国时,他必须支付一枚银币。
 世界可以由平面的第一象限表示,并且沿着直线x = y构建墙。直线下方任何一点都属于第一王国,而直线上方任何一点都属于第二王国。在线上的任何整数点处存在门(即,在点(0,0),(1,1),(2,2),...)处。墙和大门不属于任何王国。
 Fafa在位置(0,0)的门口,他想在两个王国中四处走动。他知道他将要做的动作的顺序S.此序列是一个字符串,其中每个字符代表一个移动。 Fafa将做的两个可能的动作是‘U‘(向上移动一步,从(x,y)到(x,y + 1))和‘R‘(向右移动一步,从(x,y)到( X + 1,Y))。
 Fafa想知道按照序列S在两个王国附近行走需要支付的银币数量。注意如果Fafa在没有从一个王国移动到另一个王国的情况下访问大门,他就不会支付银币。假设他没有在点(0,0)处的门处付款。即他最初是在他需要的一方。
技术分享图片

 

Input

输入的第一行包含单个整数n(1≤n≤10 5) - 步行序列中的移动次数。
 
第二行包含一个长度为n的字符串S,由描述所需移动的字符“U”和“R”组成。 Fafa将按照从左到右的顺序遵循序列S.

Output

在一行上,打印一个整数,表示Fafa需要支付的银币数量.
Examples
Input
1
U
Output
0
Input
6
RURUUR
Output
1
Input
7
URRRUUU
Output
2

解题思路:分别记录向上和向右移动的步数,如果移动到了对角线位置,并且下一次移动将要出对角线(城门和墙)到另外的国家,则需要支付一次银币。
 1 #include<stdio.h>
 2 int main()
 3 {
 4     int n,i,j,x,y,count;
 5     char s[1000000];
 6     scanf("%d",&n);
 7     getchar();
 8     gets(s);
 9     x=0,y=0;
10     count=0;
11     for(i=0;i<n;i++)
12     {
13         if(s[i]==U)
14         {
15             y++;
16         }
17         else if(s[i]==R)
18         {
19             x++;
20         }
21         if(x==y&&s[i]==s[i+1])
22         {
23             count++;
24         }
25     }
26     printf("%d
",count);
27     return 0;
28 }

 



以上是关于Fafa and the Gates(模拟)的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces 935 C Fifa and Fafa

LeetCode Walls and Gates

[Locked] Walls and Gates

286 Walls and Gates

Walls and Gates

286. Walls and Gates