1. 程式人生 > >Fafa and the Gates(模擬)

Fafa and the Gates(模擬)

cat second bubuko 技術 hat wing any 做的 整數

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\n",count);
27     return 0;
28 }



Fafa and the Gates(模擬)