原文:链接:登录—专业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 1).
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.
译文: 红色代表笛卡尔坐标系的坐标(0,0)。她有一串指令:上、下、左、右(其中“右”使x坐标增加1,“上”使y坐标增加1)。现在Red想要选择一个连续的指令子串并执行它们。Red希望指令的最终执行能通过坐标(x,y),她想知道有多少个选择选项。
输入:第一行包含三个整数n、x和y (1<n<2×105,-105 <x,y<105), -指令字符串的长度和Red希望通过的坐标。第二行包含长度为n的字符串,由字符“W”、“S”、“a”和“D”组成。——四个方向:上、下、左、右。
输出:输出一个整数,表示连续子字符串的选择选项数。
思想类似于前缀和(记录当前坐标,后续可以作为中转点):
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define endl '\n'
const int N = 1e6 + 10, M = 1e3 + 10;
int n, m, k, v[N];
map<int, int> mp;
signed main(){
IOS
int x, y;
cin >> n >> x >> y;
if(!x && !y){ //无论如何走,都可以走
cout << (n + 1) * n / 2 << endl;
return 0;
}
mp[0] ++; // 起点也要记录
string s;
cin >> s;
int xx = 0, yy = 0, ans = 0;
for(int i = 0; i < s.size(); i ++){
if(s[i] == 'W') yy ++;
else if(s[i] == 'S') yy --;
else if(s[i] == 'A') xx --;
else xx ++;
mp[xx * N + yy] ++; //当前坐标的记录
if(mp[(xx - x) * N + yy - y]){ //有中转点可以通向站点
ans += mp[(xx - x) * N + yy - y] * (n - i); //本题说有途径(x, y)即可,所以后面的(n - i)点都可以途径。
mp[(xx - x) * N + yy - y] = 0;
}
}
cout << ans << endl;
return 0;
}