Polycarp and String Transformation(E)

Polycarp and String Transformation
题意:有字符串s ,字符串t开始为空,重复以下过程直到s为空,第一步t = t + s ,第二步删去s中的全部的某字母。
现在给出最后的t串,输出开始的s串和对应的字母删除顺序。

思路:删除的字母就是t串出现的字母,既然每次都执行了t=t+s,所以后删的字母一定在t串的后面,所以只需要倒着找到不同的字母,然后把找到的字母再倒过来就是字母的删除顺序(只能倒着找,因为每次新加的s串在后面),例如:abacabaaacaac,倒着找到cab,倒过来bac为删除顺序。
找s串:从题目过程分析
•先删b,t串中b的个数除以1就是原s串b的个数
•再删a,因为删b的时候a的个数又加了一遍,所以t串中a的个数除以2就是原s串a的个数
•最后删c,毋庸置疑t串中c的个数除以3就是原s串c的个数。
以上加起来总和就是s串的字符个数,从t串左边截取下来就是s串。
判断只需要照着题目要求,把s串变成t串比较即可。

#include<iostream>
#include<iomanip>
#include<cstring>
#include<string>
using namespace std;
int a[26];//数组记录字母数
string s,t,ss,sss,ans,tmp;//tmp为空串,用于初始化其他串
int main()
{
    
    
    int T;
    cin>>T;
    while(T--)
    {
    
    
        cin>>t;
        ans=tmp;
        for(int i=t.size()-1; i>=0; i--)
        {
    
    
            if((++a[t[i]-'a'])==1)//既寻找了第一次出现的字母,又记录了每个字母的个数
                ans+=t[i];
        }
        int x=ans.size(),l=0;//ans为删除的字母
        for(int i=0; i<=(x-1)/2; i++)
            swap(ans[i],ans[x-i-1]);//变为正确的删除顺序
        for(int i=0; i<x; i++)
            l+=a[ans[i]-'a']/(i+1);//截取s串长度
        s=ss=t.substr(0,l);//找到s串
        for(int i=0; i<x; i++)//模拟题目过程
        {
    
    
            sss=tmp;
            for(int j=0; j<s.size(); j++)
                if(s[j]!=ans[i])
                    sss+=s[j];
            s=sss;
            ss+=s;
        }
        if(ss==t)//判断
            cout<<t.substr(0,l)<<" "<<ans<<endl;
        else cout<<-1<<endl;
        memset(a,0,sizeof(a));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_51443397/article/details/119827412