Command Sequence
题意
一个机器人能上下左右移动。给定一个移动的字符串,问有多少的子串可以使其按照子串的顺序来走能回到原点
题解
我打眼望过去,这本质上就是两种类型的括号匹配,要两种括号要同时匹配成功
比赛的时候讨论好解法时,当发来一个片段的时候:
到最后也没优化出来
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <map>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <sstream>
#include <unordered_map>
#define ll long long
#define ull unsigned long long
#define re return
#define pb push_back
#define Endl "\n"
#define endl "\n"
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 2e5 + 10;
const int M = 1e5 + 10;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};
struct nope{
int id;
int x;
} a[N];
int T;
int n;
char s[N];
int s1[N];
int s2[N];
int main(){
scanf("%d", &T);
while(T--){
scanf("%d", &n);
scanf("%s", s + 1);
for (int i = 1; i <= n; i++){
if(s[i] == 'U')
a[i].x = 1, a[i].id = 1;
if(s[i] == 'D')
a[i].x = -1, a[i].id = 1;
if(s[i] == 'L')
a[i].x = 1, a[i].id = 2;
if(s[i] == 'R')
a[i].x = -1, a[i].id = 2;
}
for (int i = 1; i <= n; i++){
if(a[i].id == 1){
s1[i] = s1[i - 1] + a[i].x;
s2[i] = s2[i - 1];
}
else{
s2[i] = s2[i - 1] + a[i].x;
s1[i] = s1[i - 1];
}
}
for (int i = 1; i <= n; i++){
cout << s1[i] << " ";
}
cout << endl;
for (int i = 1; i <= n; i++){
cout << s2[i] << " ";
}
cout << endl;
ll ans = 0;
for (int i = 0; i < n; i++){
}
printf("%lld\n", ans);
}
}
赛后根据上面的那个公式,我们把代码做了一下优化
相信只要懂了上面的聊天记录就能看懂下面的代码
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <map>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <sstream>
#include <unordered_map>
#define ll long long
#define ull unsigned long long
#define re return
#define pb push_back
#define Endl "\n"
#define endl "\n"
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 2e5 + 10;
const int M = 1e5 + 10;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};
int T;
int n;
char s[N];
int a[N];
int main(){
cin >> T;
while(T--){
scanf("%d", &n);
scanf("%s", s + 1);
for (int i = 1; i <= n; i++){
if(s[i] == 'U')
a[i] = 1;
if(s[i] == 'D')
a[i] = -1;
if(s[i] == 'L')
a[i] = 100000;
if(s[i] == 'R')
a[i] = -100000;
}
map<ll, int> m;
ll pre = 0;
ll ans = 0;
m[pre]++;
for (int i = 1; i <= n; i++){
pre += a[i];
if(m.find(pre) != m.end())
ans += m[pre];
m[pre]++;
}
printf("%lld\n", ans);
}
}
本篇主要作为心路历程的记录,不作为完全的题解
|