A. Jumping Ball
In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position i + 1) if the type of this bumper is '>', or one position to the left (to i - 1) if the type of the bumper at position i is '<'. If there is no such position, in other words if i - 1 < 1 ori + 1 > n, the ball falls from the game field.
Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper.
Output
Print one integer — the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position.
4
<<><
2
5
>>>>>
5
4
>><<
0
In the first sample, the ball will fall from the field if starts at position 1 or position 2.
In the second sample, any starting position will result in the ball falling from the field.
================================================================================================
题目大意:输入有n个字符组成的字符串,每个字符要么是">"要么是"<";当为前者时,位置i向右移动一位变成位置i+1(然后继续看i+1上的字符);当为后者时,位置i向左移动一位变成了位置i-1(然后继续看i-1上的字符).如果位置i移动后i+1>n或者i-1<1,则为出界。输出所有会造成出界的初始位置的数目。
题解:这题一开始没读懂题意,卡了一会(实际上水题啊);
思路一:观察每个字符串会发现只有"><"出现时,>前边的所有连续的>和<后边所有连续的<都不会出界。所以计算出字符串中所有的这种格式的字符数目sum,最后用n-sum即结果。
思路二:如果用法一,会发现处理起来有些麻烦;可以考虑它(法一)的对立面,从左边开始,连续的<一定会出界;从右边开始,连续的>一定会出界;所以,这两边续的总数,即最终结果.
代码如下:
#include <stdio.h> #include <string.h> #define maxn 200005 char str[maxn]; int cnt = 0; int main() { int n; int i,l = 0,r = 0; scanf("%d",&n); scanf("%s",str); for(i = 0; i < n; i++) if(str[i] =='<') l++; else break; for(i = n-1; i >= 0; i--) if(str[i] =='>') r++; else break; printf("%d\n",l+r); }