Codeforces 626A Robot Sequence(模拟)
A. Robot Sequence
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.
The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands.
The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code.
Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.
6
URLLDR
2
4
DLUU
0
7
RLRLRLR
12
In the first case, the entire source code works, as well as the "RL" substring in the second and third characters.
Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.
题目链接:http://codeforces.com/contest/626/problem/A
题意:在一块方格里,给出一串指令包含U,D,L,R这些字母,分别表示上下左右移动一格。问有多少个子串(包含自身)能使得物体回到出发位置。
分析:模拟一下找子串的个数即可!
解释下样例3:子串为:RL,RLRL,RLRLRL,LR,LRLR,LRLRLR,RL,RLRL,LR,LRLR,RL,LR,共12条,所以输出为12
下面给出AC代码:
1 #include <bits/stdc++.h> 2 using namespace std; 3 inline int read() 4 { 5 int x=0,f=1; 6 char ch=getchar(); 7 while(ch<'0'||ch>'9') 8 { 9 if(ch='-') 10 f=-1; 11 ch=getchar(); 12 } 13 while(ch>='0'&&ch<='9') 14 { 15 x=x*10+ch-'0'; 16 ch=getchar(); 17 } 18 return x*f; 19 } 20 int n; 21 char s[255]; 22 int main() 23 { 24 n=read(); 25 cin>>s; 26 int e=0; 27 for(int i=0;i<n;i++) 28 { 29 int a=0,b=0,c=0,d=0; 30 for(int j=i;j<n;j++) 31 { 32 if(s[j]=='U') 33 a++; 34 if(s[j]=='D') 35 b++; 36 if(s[j]=='L') 37 c++; 38 if(s[j]=='R') 39 d++; 40 if(a==b&&c==d) 41 e++; 42 } 43 } 44 cout<<e<<endl; 45 return 0; 46 }
作 者:Angel_Kitty
出 处:https://www.cnblogs.com/ECJTUACM-873284962/
关于作者:阿里云ACE,目前主要研究方向是Web安全漏洞以及反序列化。如有问题或建议,请多多赐教!
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
特此声明:所有评论和私信都会在第一时间回复。也欢迎园子的大大们指正错误,共同进步。或者直接私信我
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是作者坚持原创和持续写作的最大动力!
欢迎大家关注我的微信公众号IT老实人(IThonest),如果您觉得文章对您有很大的帮助,您可以考虑赏博主一杯咖啡以资鼓励,您的肯定将是我最大的动力。thx.
我的公众号是IT老实人(IThonest),一个有故事的公众号,欢迎大家来这里讨论,共同进步,不断学习才能不断进步。扫下面的二维码或者收藏下面的二维码关注吧(长按下面的二维码图片、并选择识别图中的二维码),个人QQ和微信的二维码也已给出,扫描下面👇的二维码一起来讨论吧!!!
欢迎大家关注我的Github,一些文章的备份和平常做的一些项目会存放在这里。