Educational Codeforces Round 87 (Rated for Div. 2) B--Ternary String

B:http://codeforces.com/contest/1354/problem/B

题意:

找出同时含有1,2,3的最短序列的长度。

解析:

比赛代码被hack了,超时。赛后看了题解,才觉得自己真是太蠢了。

p[1],p[2],p[3]来记录最后出现对应数字的位置。当三者都出现时,更新最小值。

#include<iostream>
#include<cstring>
#include<map>
#include<cstdio>
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
int p[5];
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        string s;
        cin>>s;
        p[1]=-1;
        p[2]=-1;
        p[3]=-1;
        int minn=maxn;
        int len=s.length();
        p[s[0]-'0']=0;
        for(int i=1;i<len;i++)
        {
            int md=s[i]-'0';
            p[md]=i;
            if(p[1]!=-1&&p[2]!=-1&&p[3]!=-1)
            {
                if(md==1)
                {
                    minn=min(minn,p[1]-min(p[2],p[3])+1);
                }
                if(md==2)
                {
                    minn=min(minn,p[2]-min(p[1],p[3])+1);
                }
                if(md==3)
                    minn=min(minn,p[3]-min(p[2],p[1])+1);
            }
        }

        if(minn==maxn)
            cout<<"0"<<endl;
        else
        cout<<minn<<endl;
    }
}

猜你喜欢

转载自www.cnblogs.com/liyexin/p/12918594.html