D. String Game----二分答案

本文解析了一道关于字符串匹配的编程竞赛题目,通过二分查找确定最长可删除序列,确保目标字符串仍包含于源字符串中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

D. String Game
time limit per test
2 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output

Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.

Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word ta1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya "nastya "nastya "nastya "nastya "nastya"nastya".

Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.

It is guaranteed that the word p can be obtained by removing the letters from word t.

Input

The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| < |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t.

Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).

Output

Print a single integer number, the maximum number of letters that Nastya can remove.

Examples
input
ababcba
abb
5 3 4 1 7 6 2
output
3
input
bbbabb
bb
1 6 3 4 2 5
output
4
Note

In the first sample test sequence of removing made by Nastya looks like this:

"ababcba "ababcba "ababcba "ababcba"

Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".

So, Nastya will remove only three letters.

题目链接:http://codeforces.com/problemset/problem/779/D


  16级省赛选拔防AK题,我发现cf好喜欢二分答案啊,我总感觉以前见过这个题,忘记了当时做没做出来,反正现在做出来了

题目的意思是说给你两个字符串,然后给你一串序列,然后我们按序列删除字母,删除后第一个串中还需要继续包括第二个串,求这个序列最长为多少。

匹配的时候我直接暴力的竟然没有超时,然后我们在序列中二分,然后就过了。。。好水

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
string s;
string ss;
string S;
int a[300000];
bool judge(){
    int len=ss.length();
    int top=0;
    int L=S.length();
    for(int i=0;i<L;i++){
        if(ss[top]==S[i]){
            top++;
        }
    }
    if(top==len)
        return true;
    return false;
}
int main(){
    cin>>s;
    cin>>ss;
    int len=s.length();
    for(int i=0;i<len;i++){
        scanf("%d",&a[i]);
    }
    int ans=0;
    /*for(int i=0;i<len;i++){
        s[a[i]-1]='*';
        bool flag=judge();
        if(!flag){
            break;
        }
        ans++;
    }*/
    int l=0,r=len-1;
    while(l<=r){
        int mid=(l+r)>>1;
        S=s;
        for(int i=0;i<=mid;i++){
            S[a[i]-1]='*';
        }
        bool flag=judge();
        if(!flag){
            r=mid-1;
        }
        else{
            l=mid+1;
        }
    }
    printf("%d\n",l);
    return 0;
}



package com.example.text; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.media.projection.MediaProjectionManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings; import android.util.Log; import android.view.View; import android.widget.Button; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.example.text.AI.FloatingBallService; import com.example.text.Class.goods; import com.example.text.SQL.DatabaseHelper; import com.example.text.SQL.Goods.Goods; import com.example.text.SQL.Goods.GoodsItem; import com.example.text.utils.Http; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; import android.Manifest; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private static final int REQUEST_STORAGE_PERMISSION = 1; private DatabaseHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // EdgeToEdge.enable(this); setContentView(R.layout.activity_main); // 检查存储权限 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // 权限未开启,请求用户授权 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION); } else { // 权限已开启,继续执行创建数据库的操作 createDatabase(); } if (!Settings.canDrawOverlays(this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); return; // 如果没有权限,直接退出服务 } //创建数据库 dbHelper = new DatabaseHelper(this); Intent captureIntent = ((MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE)) .createScreenCaptureIntent(); startActivityForResult(captureIntent, 101); Button button=findViewById(R.id.button2); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Settings.canDrawOverlays(MainActivity.this)) { startService(new Intent(MainActivity.this, FloatingBallService.class)); // ✅ 自动退到后台(模拟 Home 键) Intent homeIntent = new Intent(Intent.ACTION_MAIN); homeIntent.addCategory(Intent.CATEGORY_HOME); homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(homeIntent); } else { // 引导用户授权 Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); startActivity(intent); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 101 && resultCode == RESULT_OK) { Intent service = new Intent(this, FloatingBallService.class); service.putExtra("code", resultCode); service.putExtra("data", data); startService(service); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_STORAGE_PERMISSION) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // 用户授予了权限,继续执行创建数据库的操作 createDatabase(); } else { // 用户拒绝了权限,提示用户 Log.e("MainActivity", "存储权限被拒绝"); Toast.makeText(this, "存储权限被拒绝,无法继续操作", Toast.LENGTH_SHORT).show(); } } } private void createDatabase() { // 创建数据库 dbHelper = new DatabaseHelper(this); Log.d("MainActivity", "数据库创建成功"); } } 2025-07-18 09:17:38.018 2569-2630 MiEvent system_server E report:open miev fail, EventId 901003004 -t 1752801458 -paraList {"ActivityName":"com.example.text.MainActivity","Duration":10126,"PackageName":"com.example.text"} ---------------------------- PROCESS ENDED (10638) for package com.example.text ---------------------------- 2025-07-18 09:17:40.058 4285-5371 ActivityManagerWrapper com.miui.home E getRecentTasks: mainTaskId=10275 userId=0 windowMode=1 baseIntent=Intent { act=android.intent.action.MAIN flag=270532608 cmp=ComponentInfo{com.example.text/com.example.text.MainActivity} } 2025-07-18 09:17:40.416 1425-1425 vendor.qti...al-service ven...qti.hardware.perf-hal-service E ExtendedPerfBoost: extended_perfboost_verification() 738: Ok, set boost params. hintid=4225 hinttype=1 prio=3, clientpid=2569 packagename=com.example.text params=boost:1 cpu0:1804800 cpu4:2496000 cpu7:2592000 cpumask:ff 2025-07-18 09:17:40.459 10872-10872 Zygote usap64 E process_name_ptr:10872 com.example.text 2025-07-18 09:17:40.523 27603-3228 SuggestManager com.miui.securitycenter.remote E openApp name = com.example.text 2025-07-18 09:17:40.534 27603-28288 AntiFraud com.miui.securitycenter.remote E hookDetectUnsafeAppStart error, android.content.pm.PackageManager$NameNotFoundException: com.example.text at android.app.ApplicationPackageManager.getApplicationInfoAsUser(ApplicationPackageManager.java:515) at android.app.ApplicationPackageManager.getApplicationInfo(ApplicationPackageManager.java:498) at android.app.ApplicationPackageManager.getApplicationInfo(ApplicationPackageManager.java:492) at w2.b.f(Unknown Source:12) at w2.b$c.onForegroundInfoChanged(Unknown Source:21) at com.miui.gamebooster.mutiwindow.b$a.onForegroundInfoChanged(Unknown Source:152) at miui.process.IForegroundInfoListener$Stub.onTransact(IForegroundInfoListener.java:86) at android.os.Binder.execTransactInternal(Binder.java:1351) at android.os.Binder.execTransact(Binder.java:1282) 2025-07-18 09:17:40.546 8279-10833 SuggestManager com.miui.securitycenter.remote E openApp name = com.example.text 2025-07-18 09:17:40.549 4285-5371 ActivityManagerWrapper com.miui.home E getRecentTasks: mainTaskId=10276 userId=0 windowMode=1 baseIntent=Intent { act=android.intent.action.MAIN flag=268435456 cmp=ComponentInfo{com.example.text/com.example.text.MainActivity} } ---------------------------- PROCESS STARTED (10872) for package com.example.text ----------------------------
最新发布
07-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值