B. Ilya and Queries(动态规划)Codeforces Round #186 (Div. 2)

原题链接: http://codeforces.com/contest/313/problem/B

在这里插入图片描述
测试样例

input

4
3 4
2 3
1 6
2 6
output
1
1
5
4
input
#…###
5
1 3
5 6
1 5
3 6
3 4
output
1
1
2
2
0

题意: 给你一个字符串 s s s,接下来有 m m m次询问,每次询问会给定区间 [ l , r ] [l,r] [l,r],你需要回答在这区间中有多少对 s i = s i + 1 s_i=s_{i+1} si=si+1的数量,其中 l ≤ i < r l\leq i<r li<r

解题思路: 这道题我们很容易想到暴力,但时间复杂度确实过大,我们需要进行预处理,即可以用动态规划来记忆化前 k k k个字符的数量对数,最后利用其相减即可。

AC代码

/*
*blog:https://blog.csdn.net/hzf0701
*邮箱:unique_powerhouse@qq.com
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*/
#include<bits/stdc++.h>
#define rep(i,a,n) for(int i=a;i<=n;i++)
#define per(i,n,a) for(int i=n;i>=a;i--)

using namespace std;

typedef long long ll;
const int maxn=1e5+10;//数组所开最大值
const int mod=1e9+7;//模
const int inf=0x3f3f3f3f;//无穷大

string s;
int m,l,r;
int pre[maxn];
void solve(){
    while(cin>>s){
        //利用前缀数组。
        int len=s.size();
        rep(i,1,len-1){
            pre[i]=pre[i-1]+(s[i]==s[i-1]);
        }
        cin>>m;
        rep(i,1,m){
            cin>>l>>r;
            l--,r--;
            cout<<pre[r]-pre[l]<<endl;
        }
    }
}
int main(){
    solve();
    return 0;
}

posted @ 2022-03-26 16:49  unique_pursuit  阅读(28)  评论(0)    收藏  举报