Codeforces 1295C Obtain The String (二分)

传送门

题意:

给两个字符串 s , t s,t s,t
z z z为一个空串
问对 s s s进行多少操作能将 z z z变成 t t t
每次操作为,选s的一些字串(可以不连续,但顺序不能乱),让把这个字串加到Z的后面
输出最少操作的次数,如果 z z z不能变成 t t t,输出-1

思路:

把字符串放入vector,或者二维数组里,因为只有小写字母,30个空间已足够
如果t的字符在s中找不到,那肯定输出-1
如果能找到为了使操作数最少,肯定用比较靠前且满足题意的
找位置的时候二分即可用upper_bound,upper_bound的用法

代码:

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <vector>
#include <math.h>
#include <map>
#include <queue>
#include <set>
using namespace std;
typedef long long ll;
const int maxn=1e5+50;
char s[maxn],t[maxn];

int main()
{
    int q;
    scanf("%d",&q);
    while(q--){

        scanf("%s %s",s,t);
        vector<int>p[30];
        for(int i=0;s[i];i++){
            p[s[i]-'a'].push_back(i);
        }
        int ans=1,flag=1;
        int pos,ppos=-1;//pos为当前正在找的字符k在p[k]中的位置,ppos当前在s串中的位置
        for(int i=0;t[i];i++){
            int k=t[i]-'a';
            if(p[k].size()==0){//在t中找不到
                flag=0;
                break;
            }
            pos=upper_bound(p[k].begin(),p[k].end(),ppos)-p[k].begin();//ppos当前在s串中的位置,看在p[k]的哪个位置,且能不能满足
            if(pos==p[k].size()){//如果字符为k的找到头了,说明需要从头再找,ans++
                ans++;
                pos=0;
            }
            ppos=p[k][pos];
        }
        if(!flag)printf("-1\n");
        else printf("%d\n",ans);
    }
    return 0;
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值