题解:2169B - Drifting Away

· · 题解

原题链接:CF 2169B

题意简述

给定一个仅由 <、> 和 * 组成的字符串。在串中任意选择一个字符作为起始点,按以下规则移动:

询问能够移动的最大路程。如果存在方案可以无限移动,输出 -1。

解题思路

我们将这个问题拆分成两个子问题:

  1. 是否能无限移动
  2. 如果不能,最多能移动多少路程

先解决第一个问题。

不难发现 * 是最难处理的部分,因为它所指的方向是不固定的。
考虑处理一个仅包含 < 和 > 的字符串,思考什么情况下可以无限移动:

这个结论是显而易见的。

现在我们把 * 加回来。位于 * 时,可以自选方向,我们不妨理解为可以将当前位置改成一个 < 或 >。根据上面的结论,只要我们能由此构造出形如 >< 的子串,就可以无限地移动下去。

考虑什么情况下可以构造出满足条件的子串:

那么我们只要在字符串中查找是否存在如上子串就可以完成判断。

接下来我们解决第二个子问题:最多能移动多少路程。

不难想到,一个不可以在其中无限移动的字符串一定形如:

\underbrace{<<\dots <}_{若干个<} \underbrace{*}_{最多一个*} \underbrace{>>\dots >}_{若干个>}

那么最优的方案一定是这两种方案中的一种:

哪个方案更优呢?很显然,如果 > 的数量比 < 多,则第一个方案更优,反之第二个方案更优。

所以我们只需要统计两种符号的数量即可得出答案。

AC Code

#include<bits/stdc++.h>
using namespace std;
int const N=3e5+1;
char S[N];
int T,len,ans;
inline long long read(){
    char ch=getchar();
    long long res=0;
    int f=1;
    while(!isdigit(ch)){
        if(ch=='-'){
            f=-1;
        }
        ch=getchar();
    }
    while(isdigit(ch)){
        res=(res<<1)+(res<<3)+(ch^48);
        ch=getchar();
    }
    return res*f;
}
inline void read_str(char (&S)[N],int &len){
    len=0;
    char ch=getchar();
    while(ch=='<'||ch=='>'||ch=='*'){
        S[++len]=ch;
        ch=getchar();
    }
    S[len+1]='.';
}
inline void print(long long x){
    if(x<0){
        putchar('-');
        x=-x;
    }
    if(x>9){
        print(x/10);
    }
    putchar((x%10)^48);
}
inline bool judge(char (&S)[N]){
    for(int i=2;i<=len;i++){
        if(S[i]=='*'){
            if(S[i-1]=='>'||S[i-1]=='*'){
                return 0;
            }
        }
        else if(S[i]=='<'){
            if(S[i-1]=='>'||S[i-1]=='*'){
                return 0;
            }
        }
    }
    return 1;
}
inline void work(char (&S)[N]){
    int pos=1,num_1=0,num_2;
    while(S[pos]=='<'){
        num_1++;
        pos++;
    }
    ans=max(num_1+(S[pos]=='*'),len-num_1);
}
int main(){
    T=read();
    while(T--){
        read_str(S,len);
        if(!judge(S)){
            ans=-1;
        }
        else{
            work(S);
        }
        print(ans);
        putchar('\n');
    }
    return 0;
}
/*
 ____   _                     _
|  __| | |                   | |  __           _    __/\__
| |__  | |___   _____   ___  | | / /  _____   | |   \    /
|__  | |  _  | |  _  | |  _| | |/ /  |  _  | |   |  /____\
 __| | | | | | | |_| | | |   | |\ \  | |_| |  | |
|____| |_| |_| |___|_| |_|   |_| \_\ |___|_|  |_|           */