hdoj 1867 A + B for you again【kmp,前缀与后缀的匹配】

A + B for you again

Problem Description
Generally speaking, there are a lot of problems about strings processing. Now you encounter another such problem. If you get two strings, such as “asdf” and “sdfg”, the result of the addition between them is “asdfg”, for “sdf” is the tail substring of “asdf” and the head substring of the “sdfg” . However, the result comes as “asdfghjk”, when you have to add “asdf” and “ghjk” and guarantee the shortest string first, then the minimum lexicographic second, the same rules for other additions.
 

Input
For each case, there are two strings (the chars selected just form ‘a’ to ‘z’) for you, and each length of theirs won’t exceed 10^5 and won’t be empty.
 

Output
Print the ultimate string by the book.
 

Sample Input
  
  
asdf sdfg asdf ghjk
 

Sample Output
  
  
asdfg asdfghjk
 

题目大意:输入两个字符串啊a和b,然后把两个字符串收尾相连,相连时候,把a的后缀和b的前缀重合【b的后缀和a的前缀重合】,还要求输出的合并字符串字典序最小且长度最短。

思路:首先比较两个字符串的长度,若一样长,则比较两个字符串的字典序,字典序小的放前面,

        然后再计算a的后缀和b的前缀的匹配长度len1,接着计算b的后缀和a的前缀的匹配长度len2,如果len1<len2,则b在前,a在后;否则,a在前,b在后。

Accept代码【C++】【46MS】【2300K】

#include <cstdio>
#include <cstring>

using namespace std;

char str_1[100001], str_2[100001];
int p[100001];
int total;

void Kmp_huan(char *k, int len) {
    int i = 0, j = -1;
    p[0] = -1;
    while(i + 1 < len) {
        if(j == -1 || k[i] == k[j]) {
        	i++, j++;
        	if(k[i] == k[j])
        		p[i] = p[j];
        	else
        		p[i] = j;//优化,即数据结构书中求的nextval数组【http://blog.csdn.net/nailnehc/article/details/49184599】
		}
        else
            j = p[j];
    }
}

int KMP(char *s, char *t, int len_s, int len_t) {
    int i = 0, j = 0;
    memset(p, 0, sizeof(p));
    Kmp_huan(t, len_t);
    while(i < len_s){ 
        while(s[i] != t[j]) {
        	if(p[j] == -1) {
        		j = 0;
        		break;
			}
			j = p[j];
		}
		if(s[i] == t[j])
			j++;
		i++;
    }
	return j;
}

int main() {
    int x = 0, y = 0;
    int len_1, len_2;
    while(~scanf("%s %s", str_1, str_2)) {//笔者在这里吃了瘪,注意哈<---------  看过来 本来是【while(1) {   scanf()...   }】Output Limit Exceeded
        len_1 = strlen(str_1);
        len_2 = strlen(str_2);
        x = KMP(str_1, str_2, len_1, len_2);
        y = KMP(str_2, str_1, len_2, len_1);
        if(x == y) {
            if(strcmp(str_1, str_2) > 0) {
                printf("%s", str_2);
                printf("%s\n", str_1 + y);
            }
            else {
                printf("%s", str_1);
                printf("%s\n", str_2 + y);
            }
        }
        else if(x > y){
            printf("%s", str_1);
            printf("%s\n", str_2 + x);
        }
        else {
            printf("%s", str_2);
            printf("%s\n", str_1 + y);
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值