2024牛客暑期多校训练营2 H Instructions Substring

链接:登录—专业IT笔试面试备考平台_牛客网
来源:牛客网
 

题目描述

Red stands at the coordinate (0,0)(0,0)(0,0) of the Cartesian coordinate system. She has a string of instructions: up, down, left, right (where `right' increases the x-coordinate by 111, and `up' increases the y-coordinate by 111).

Now Red wants to select a continuous substring of instructions and execute them. Red hopes that the final execution of the instructions can pass through the coordinate (x,y)(x,y)(x,y). She wants to know how many selection options there are.

输入描述:

The first line contains three integers n, x, and y (1≤n≤2×105,−105≤x,y≤105), — the length of the instruction string and the coordinates Red hopes to pass through.

The second line contains a string of length nnn, consisting of the characters 'W', 'S', 'A', and 'D'. — the four directions: up, down, left, and right, respectively.

输出描述:

Output one integer representing the number of selection options for the continuous substring.

示例1

输入

6 1 1
ASAWDD

输出

3

说明

Choosing "AWDD", "WD", or "WDD" are all valid.

示例2

输入

4 0 0
WWWS

输出

10

说明

Any substring can pass through (0,0), as it is the starting point.

题目大意:给你一个长度为n的字符串,你的起点是(x,y)点,终点是(x,y),字符串中的‘W’是向上,'S'是向下,‘A’是向左,‘D’是向右。你可以截取字符串中的子串来判断能不能经过(x,y)点,让你求有多少种方法能经过(x,y)点。

思路:定义一个(tx,ty)来表示当前坐标,然后根据字符串的顺序进行移动,每经过一个点就记录经过这个点的次数k,当你遇到(tx-x,ty-y)这个点出现过的话,就说明从坐标为(tx-x,ty-y)对应的这个字符的下一个字符开始移动,到当前这个字符,这一子串刚好能从(0,0)跑到终点(tx,ty),就把从这个字符开始到最后一位字符的个数加起来乘上k计入最后的答案,k记得清零。(注意:当起点等于终点的时候直接输出这个字符串字串的个数)。

#include
using namespace std;
#define int long long
#define pii pair
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
signed main()
{
	IOS
	map mp;
	int n,x,y,tx=0,ty=0,sum=0;
	cin >> n >> x >> y;
	if(x==0 && y==0){
		cout << (1+n)*n/2 << endl;
		return 0;
	}
	mp[{tx,ty}]=1;
	for(int i=1;i<=n;i++){
		char ch;
		cin >> ch;
		if(ch=='A') tx--;
		else if(ch=='D') tx++;
		else if(ch=='W') ty++;
		else ty--;
		if(mp[{tx-x,ty-y}]){
			sum+=(n-i+1)*mp[{tx-x,ty-y}];
			mp[{tx-x,ty-y}]=0;
		}
		mp[{tx,ty}]++;
	}
	cout << sum << endl;
	return 0;
}

你可能感兴趣的:(算法)