题目描述
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 nnn, xxx, and yyy (1≤n≤2×105,−105≤x,y≤105)(1 \leq n \leq 2 \times 10^5, -10^5 \leq x, y \leq 10^5)(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′'W'′W′, ′S′'S'′S′, ′A′'A'′A′, and ′D′'D'′D′. — the four directions: up, down, left, and right, respectively.
输出描述:
Output one integer representing the number of selection options for the continuous substring.
#include<bits/stdc++.h>
using namespace std;
#define int long long
map<pair<int,int>,int> mp;
int ax[200040],ay[200050];
signed main(){
int n,x,y;
cin>>n>>x>>y;
for(int i=1;i<=n;i++){
char e;
cin>>e;
ax[i]=ax[i-1];//前缀和
ay[i]=ay[i-1];
if(e=='A'){
ax[i]--;
}else if(e=='W'){
ay[i]++;
}else if(e=='S'){
ay[i]--;
}else{
ax[i]++;
}
}
int ans=0;
for(int i=n;i>=0;i--){
mp[{ax[i],ay[i]}]=i;//输入位置
int r=mp[{ax[i]+x,ay[i]+y}];//如果出现过上一位置 条件满足
if(r) ans+=n-r+1;
}
cout<<ans<<endl;
return 0;
}
考虑计算出第 i 个操作执行完后的坐标(nx[i],ny[i]),执行区间 [l,r] 内的操作后的坐标为 (nx[r]-nx[l-1],ny[r]-ny[l-1]),考虑枚举符合要求的区间的左端点 l ,符合要求的右端点一定是 (nx[l-1]+x,ny[l-1]+y)。开个 map 记录,每次找到最靠左符合要求的右端点 r ,在 r 之后的一定也符合条件,所有 ans+=n-r+1*(问来的解释^.^____lyhqwq)