HDU 7108 Command Sequence

Problem Description

There is a robot that can move by receiving a sequence of commands.

There are four types of command in the command sequence:
 


  • U: robot moves one unit up.
  • D: robot moves one unit down.
  • L: robot moves one unit left.
  • R: robot moves one unit right.

     



Now, given a command sequence of length n. You need to find out how many substrings of the command sequence satisfy that if the robot execute the substring command, it can return to the starting position.

A substring is a contiguous sequence of characters within a string. For instance, "the best of" is a substring of "It was the best of times". For example, "Itwastimes" is a subsequence of "It was the best of times", but not a substring.

 

Input

This problem contains multiple test cases.

The first line contains an integer t (1≤t≤20) indicating the number of test cases.

For each test case, the first line contains one integer n (2≤n≤105).

The second line contains a UDLR string of length n.

 

Output

For each test case, output one line one integer indicating the answer.

 

Sample Input

 
 

1 6 URLLDR

 

Sample Output

 
 

2

 题意:给定一个命令序列,分别控制机器人向上下左右四个方向移动,求有多少个命令序列的子序列可以使机器人回到原点

思路:可以发现要使机器人回到原点必须要使上下和左右的移动次数相等,可以利用前缀和求出每一步的前缀和,而后通过判断和是否相等来判断机器人是否会回到原点

AC代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<map>
using namespace std;

#define ll long long
const int N=100010;

ll sum[N];
string s;
map<char,int> mp={{'U',1},{'D',-1},{'L',N},{'R',-N}};

int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		map<ll,int> a;
		int n;
		cin>>n>>s;
		a[0]=1;
		ll res=0;
		
		for(int i=0;i<n;i++)
		{
			sum[i]=sum[i-1]+mp[s[i]];
			if(a[sum[i]])
				res+=a[sum[i]];
			a[sum[i]]++;
		}
		cout<<res<<endl;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Double.Qing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值