思路:最长的碎片和最短的碎片的组合中肯定有答案。所以先求长度,然后组合他们,最后检测组合结果字符串是否确保输入的碎片字符串都在其开始或结尾处。
总结:代码编写边注释,当你注释写不好的时候,说明你的思路也不是很清晰,请停下来思考,理清思路。下面这段代码是我注释得最详细的,因为我体会到,当自己写的程序不能AC的时候,搜搜看看别人没有注释的代码会更加让自己烦躁。
#include<stdio.h> #include<string.h> void Reverse(char *strDest,const char *strSrc) { int len = strlen(strSrc); int i; for(i = 0;i < len; i++) { strDest[i] = strSrc[len - i - 1]; } strDest[i] = '\0'; } int IsWholeFile(char (*str)[260],int StrSize,char* strTmp)/*is strTmp the whole file*/ { int i; char *pos,*rpos; char strRvrs[260];/*reverse the str[i] in order to find in a reverse way*/ char strRvrsTmp[260]; for(i = 1;i <= StrSize;i ++)/*if the strTmp is the whole file,then every str[i] should be find in the strTmp'start or end pos*/ { pos = strstr(strTmp,str[i]); if(NULL == pos )/*not find */ { return 0; } if(pos != strTmp )/*str[i] must at start pos of the string or at the end of the string*/ { Reverse(strRvrsTmp,strTmp);/*reverse the strTmp*/ Reverse(strRvrs,str[i]);/*reverse the str[i]*/ rpos = strstr(strRvrsTmp,strRvrs);/*then here can implement the function of rfind*/ if( rpos != strRvrsTmp)/*not at the end,due to the reverse operation,finding str[i] in the end of strTmp means,in fact,rpos isthe start position of the strRvrsTmp*/ { return 0; } } } return 1; } void RecoverFile(char (*str)[260],int nMaxlen,int nMinlen,int nStrSize) { int i,j; char strRst[8][260];/*possible file*/ char tmp[260]; int count = 0; for(i = 1;i <= nStrSize;i ++) { if(strlen(str[i]) == nMaxlen)/*find the longest string*/ { for(j = 1;j <= nStrSize;j ++) { if(strlen(str[j]) == nMinlen)/*find the shortest string*/ { strcpy(tmp,str[i]); strcat(tmp,str[j]); strcpy(strRst[count] ,tmp);/*recover in a way longest-shorest*/ count++; strcpy(tmp,str[j]); strcat(tmp,str[i]); strcpy(strRst[count] ,tmp);/*recover in a way shortest-longest*/ count++; } } } } for(i = 0;i < count;i ++)/*there are at most 8 possible answer,test each of them*/ { if(IsWholeFile(str,nStrSize,strRst[i]))/*test weather the string is whole file*/ { strcpy(str[0],strRst[i]); return ; } } } int main() { char str[150][260]; int nTest,i; int nMax_len; int nMin_len,nLength; char input[256]; scanf("%d",&nTest); getchar();getchar(); while(nTest --) { i = 0; nMax_len = 0; nMin_len = 256; strcpy(str[0],""); while(gets(input) && strlen(input) != 0) { i ++; strcpy(str[i],input); nLength = strlen(str[i]); if(nLength > nMax_len)/*get the max len*/ nMax_len = nLength; if(nLength < nMin_len)/*get the min len*/ nMin_len = nLength; } if(2 == i)/*if there are just two string,concatenate them and output*/ { strcpy(str[0],strcat(str[1],str[2])); } else RecoverFile(str,nMax_len,nMin_len,i);/*recover the file,only use the file whose length is max or min length*/ printf("%s\n",str[0]);/*rememner the enter*/ if(nTest) printf("\n");/*out put the blank line*/ } return 0; }
时间: 2024-10-11 06:05:34