D. Camp Schedule

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

题意:输入一个字符串S,和字符串t,(s,t都由‘0’,‘1’组成),s串中的‘0’,‘1’个数不变,要使s中包含最多的子串t,求s串;

可将s串重组,只要0,1个数不变就行,求t的前缀,看是否有相同,即kmp;来构造s串

#include <iostream>
#include <algorithm>
#include <stack>
#include <stdio.h>
#include<cstring>
#include<string.h>
using namespace std;
string s,t,str;
int   next2[500005];
void getnext2()
{
    int j=0,k=-1;
    next2[0]=-1;
    while(j<t.size()){
        if(k==-1||t[j]==t[k]){
            j++,k++;
            next2[j]=k;
        }
        else
            k=next2[k];
    }
}
int main()
{
    int len1,len2,ans=0;
    cin>>s>>t;
    len1=s.size();
    len2=t.size();
    getnext2();
    int cnt0=0,cnt1=0;
    for(int i=0;i<len1;i++){
        if(s[i]=='0')cnt0++;
        else
            cnt1++;
    }
    if(len1<len2)cout<<s<<endl;
    else{
            int j=0;
        while(cnt0>0&&cnt1>0){
            if(j>=len2)j=next2[j];
            if(t[j]=='0'){
                cnt0--;
                str+='0';
            }
            if(t[j]=='1'){
                cnt1--;
                str+='1';
            }
            j++;
        }
        while(cnt0){
            cnt0--;
            str+='0';
        }
         while(cnt1){
            cnt1--;
            str+='1';
        }
        cout<<str<<endl;
    }


    return 0;

}
发布了97 篇原创文章 · 获赞 3 · 访问量 9448

猜你喜欢

转载自blog.csdn.net/foolishpichao/article/details/97248981