2024牛客多校 H.Instructions Substring

题目描述

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

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值