1. 程式人生 > >C. Prefixes and Suffixes (string函式)

C. Prefixes and Suffixes (string函式)

題目連結:https://codeforces.com/contest/1092/problem/C

題意:給你2*n-2的字元子串,每個子串要麼是字首,要麼是字尾,讓你從中猜出來。

題解:我們直接找最長的兩個子串,顯然由這兩個能推出整個串。

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<iostream>

using namespace std;

bool book[200];
string s[200];

int main()
{
    int n;

//    ios::sync_with_stdio(0);

    while(~scanf("%d",&n))
    {
        string s1="q",s2="r",P;

        for(int i=1;i<=2*n-2;i++){
            cin>>s[i];
            if(s1.size()<s[i].size()) s1=s[i]; ///找到最長的兩個子串
            else if(s1.size()==s[i].size()) s2=s[i];
        }

        int num=0;

        for(int i=1;i<=2*n-2;i++){
            if(s1.substr(0,s[i].size())==s[i]){
                if(s[i]!=s2) ++num;
            }
        }

        ///假設超過一半,且s1的最長字尾等於s2的最長字首,說明s1是字首
        if(num>=(2*n-2)/2&&s1.substr(1,s1.size()-1)==s2.substr(0,s2.size()-1))
            P=s1;
        else P=s2;

        memset(book,true,sizeof(book));

        for(int i=1;i<=2*n-2;i++)
        {
            if(P.substr(0,s[i].size())==s[i]&&book[s[i].size()]){
                printf("P");
                book[s[i].size()]=0;
            }
            else
                printf("S");
        }
        puts("");


    }
    return 0;
}