Educational Codeforces Round 81
Problem C
- 题意
问你要往空串 z z z 中增加几次 s s s 的子序列才能得到串 t t t ,如果不能得到输出 − 1 -1 −1 。
- 思路
记录 s s s 串中每个字母的位置,然后遍历 t t t 串,二分查找大于上一个字母的位置 l a s t last last ,如果没有满足的,则 c n t cnt cnt++ 。
注:不要问为什么要用二分。
我一直以为是因为我用的 S T L STL STL 的缘故。为啥就没想到要用二分优化呢。菜吧!!!
- 代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e5+10,mod=1e9+7;
#define PII pair<int,int>
// #define x first
// #define y second
#define PB push_back
void solve()
{
map<char,vector<int> > mp;
string s,t;cin>>s>>t;
for(int i=0;i<s.size();i++){
mp[s[i]].push_back(i);
}
int cnt=0;
int last=s.size();
for(int i=0;i<t.size();i++){
if(mp[t[i]].size()==0){
cout<<-1<<endl;return;
}
bool flag=0;
int p=upper_bound(mp[t[i]].begin(),mp[t[i]].end(),last)-mp[t[i]].begin();
if(p>=mp[t[i]].size()){
last=(mp[t[i]][0]);cnt++;
}
else{
last=mp[t[i]][p];
}
}
cout<<cnt<<endl;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--)
solve();
}
Problem B
- 题意
给你一个长度为 n ( 1 ⩽ n ⩽ 1 0 5 ) n(1\leqslant n\leqslant10^{5}) n(1⩽n⩽105)的串,定义串 t t t 是 s s s 的无限循环。
定义一个前缀的平衡值为前缀中 0 0 0 的个数减 1 1 1 的个数,空串算一个前缀。
给定一个 x ( − 1 0 9 ⩽ x ⩽ 1 0 9 ) x(-10^{9}\leqslant x \leqslant 10^{9}) x(−109⩽x⩽109)
问有多少个前缀的平衡值等于 x x x.
- 思路
我们先处理出整个串 S S S 的平衡值 p p p
定义 S S S 串中长度为 i i i 的前缀的平衡值为 w i w_i wi。
于是我们要求的就是方程 k p + w i = x kp+w_i=x kp+wi=x 中的自然数解个数。
先把 p = 0 p=0 p=0 的情况判掉,遍历一遍如果还存在 w i = x w_i=x wi=x,则有无穷多个解,否则有 0 0 0 个。
当 p ≠ 0 p\neq0 p=0 时,就得到 k = x − w i p k= \frac{x-w_i}{p} k=px−wi 。
然后遍历 i i i 对于每个 w i w_i wi ,若 x − w i x-w_i x−wi 能被 p p p 整除,且计算出来的 k k k 为自然数,则答案加1.
最后 x = 0 x=0 x=0 时,因为空串要考虑,所以答案加1.
- 代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e5+10,mod=1e9+7;
#define PII pair<int,int>
// #define x first
// #define y second
#define PB push_back
void solve()
{
ll n,x;string s;
cin>>n>>x>>s;
ll p=0;
for(ll i=0;i<s.size();i++){
if(s[i]=='0')p++;
else p--;
}
if(p==0){
ll ans=0,w=0;
for(ll i=0;i<s.size();i++){
if(s[i]=='0')w++;
else w--;
if(w==x)ans++;
}
if(ans)cout<<-1<<endl;
else cout<<0<<endl;
return;
}
ll ans=0,w=0;
for(ll i=0;i<s.size();i++){
if(s[i]=='0')w++;
else w--;
if((x-w)%p==0&&(x-w)/p>=0)ans++;
}
if(x==0)ans++;
cout<<ans<<endl;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--)
solve();
}