首页 > 代码库 > HDU 1867 A + B for you again
HDU 1867 A + B for you again
题目:
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
题意描述:
输入两个串
输出首先保证输出结果最短的一个,其次输出两个串的字典序
解题思路:
这题的坑还是挺多的,比如需要进行两次匹配,从而求得两串不同顺序的最大的相似度,才能保证输出最短,还有是按照两个串的字典序,不是单个字母。
具体思路:使用两次KMP返回两个相似度赋值给a和b,当a==b时输出
字典序,否则根据情况输出最短的匹配结果即可。
代码实现:
1 #include<stdio.h> 2 #include<string.h> 3 char s[500100],t[500100]; 4 int l1,l2; 5 int kmp(char s[],char t[],int l1,int l2); 6 void get_next(char t[],int next[],int l2); 7 int next[500100]; 8 int main() 9 { 10 int a,b,i; 11 while(scanf("%s%s",s,t) != EOF) 12 { 13 l1=strlen(s); 14 l2=strlen(t); 15 a=kmp(s,t,l1,l2);//返回两串的相似度 16 b=kmp(t,s,l2,l1); 17 //printf("a=%d b=%d\n",a,b); 18 if(a==b) 19 { 20 if(strcmp(s,t)>0)//大于返回1,写出==1 21 { 22 printf("%s",t); 23 printf("%s",s+a); 24 } 25 else 26 { 27 printf("%s",s); 28 printf("%s",t+b); 29 } 30 } 31 else 32 { 33 if(a>b)//输出相似度最高的那一组 34 { 35 printf("%s",s); 36 printf("%s",t+a); 37 } 38 else 39 { 40 printf("%s",t); 41 printf("%s",s+b); 42 } 43 } 44 printf("\n"); 45 } 46 return 0; 47 } 48 int kmp(char s[],char t[],int l1,int l2) 49 { 50 int i,j; 51 get_next(t,next,l2); 52 i=0;j=0; 53 while(i<l1) 54 { 55 if(j==-1 || s[i]==t[j]) 56 { 57 i++; 58 j++; 59 } 60 else 61 j=next[j]; 62 } 63 //printf("j==%d\n",j); 64 return j; 65 } 66 void get_next(char t[],int next[],int l2) 67 { 68 int i,j; 69 i=1;j=0; 70 next[0]=-1; 71 while(i < l2) 72 { 73 if(j==-1 || t[i]==t[j]) 74 { 75 i++; 76 j++; 77 next[i]=j; 78 } 79 else 80 j=next[j]; 81 } 82 /*for(i=0;i<=l2;i++) 83 printf("%d ",next[i]); 84 printf("\n");*/ 85 }
易错分析:
给几组测试数据吧
a
aaa
aaa
a
aaa
aaa
aaasdf
sdfggg
zxcv
asdf
asdfasdf
sdf
HDU 1867 A + B for you again
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。