B. Non-Substring Subsequence
题意
给你一个长度为n的01字符串,然后有q次询问,每次询问为l,r,问你有没有不连续的子序列与l,r这段区间内的字符串相等
思路
刚开始的思路比较奇怪,以为自己猜到了重点,结果vp完以后发现只需要判断第一位和最后一位即可。
刚开始我是想如果没有其他解,那么一定是从刚开始连续一直到结尾的这一种解,但是我似乎没有想到l,r区间本身就是这样的。于是我判断了第一位开始是否有r-l位连续的,如果有的话我需要判断下一位的位置是否有多种,如果没有r-l位连续的话,一定是有解的。
在写双指针的时候一定要考虑清楚边界的判断,需要手动模拟特殊情况。
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
typedef long long LL;
//#define int long long
void solve() {
int n, q; cin >> n >> q;
string str; cin >> str;
int len = str.size();
while (q --) {
int i = 0, j = len - 1;
int l, r; cin >> l >> r;
int il = 0, jl = r - l;
string t = str.substr(l - 1, r - l + 1);
int cnt = 0;
while (str[i] != t[il] && i < j) ++i;
while (str[i] == t[il] && i < j && cnt < r - l) {
++i, ++il; ++cnt;
}
if (cnt == r - l) {
while (str[j] != t[jl] && i < j) --j;
if (str[j] == t[jl] && j == i) cout << "NO\n";
else if (str[j] == t[jl]) cout << "YES\n";
else cout << "NO\n";
} else {
while (cnt < r - l + 1 && i <= j) {
while (str[i] != t[il] && i <= j) ++i;
if (str[i] == t[il] && i <= j) ++cnt,++i,++il;
}
if (cnt == r - l + 1) {
cout << "YES\n";
}else cout << "NO\n";
}
}
}
signed main() {
int T = 1;
// scanf("%d", &T);
cin >> T;
while (T--) {
solve();
}
}
正常解法
如果有多种解那么l,r区间内的第一位和最后一位一定有一个有多种选择。所以只需要判头判尾
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
typedef long long LL;
//#define int long long
void solve() {
int n, q; cin >> n >> q;
string str; cin >> str;
while (q--) {
int l, r ; cin >> l >> r;
--l, --r;
int f1 = 0, f2 = 0;
for (int i = 0 ; i < l; ++i) {
if (str[i] == str[l])f1 = 1;
}
for (int i = r + 1; i < n; ++i) {
if (str[i] == str[r]) f2 = 1;
}
if (f1 || f2) cout << "YES\n";
else cout << "NO\n";
}
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
int T = 1;
// scanf("%d", &T);
cin >> T;
while (T--) {
solve();
}
}