(1)回文词是一种对称的字符串,也就是说,一个回文词,从左到右读和从右到左读得到的结果是一样的,任意给定一个字符串,通过插入若干字符都可以变成一个回文词,请设计一个算法求出给定字符串变成回文词所需插入的最少字符数。(如Ab3bd在插入两个字符后可以变成dAb3bAd或Adb3bdA,但插入两个以下的字符无法使它变成一个回文词。)别看答案,想一个更好的算法
#include<stdio.h>
#include<string.h>
int min;       /* min为最小插入字符数 */
int ishw(char string[5001])   /* 判断字符串string是否为回文词 */
{
 int i;
 for(i=0;i<strlen(string) && i<strlen(string)-1-i;i++)
  if(string[i]!=string[strlen(string)-1-i])
   return 0;
 return 1;
}
void getmin(int len,char input[5001]) /* 得到最小插入字符数 */
{
 char nextstring[5001];
 int i,j,ishwen=0;
 if(len<min)
 {
  if(ishw(input))
    min=len;
  else
  {
   for(i=0;i<strlen(input) && i<strlen(input)-i-1;i++)
   {
    if(input[i]!=input[strlen(input)-i-1])
     break;
    else
    {
     input[i]=input[strlen(input)-i-1]='`';
     ishwen=1;
    }
   }
   if(!ishwen)
   {
    for(i=0;i<strlen(input);i++)
     nextstring[i]=input[i+1];
    getmin(len+1,nextstring);
    strcpy(nextstring,input);
    nextstring[strlen(nextstring)-1]='\0';
    getmin(len+1,nextstring);
   }
   else
   {
    for(j=0,i=0;i<strlen(input);i++)
     if(input[i]!='`')
      nextstring[j++]=input[i];
    nextstring[j]='\0';
    getmin(len,nextstring);
   }
  }
 }
}
void main(void)
{
 char input[5001],slen[5]; /* input为待处理的字符串 */
 int i;
 FILE *fp;
 min=10000;
 fp=fopen("palin.in","r");
 if(fp==NULL)
 {
   printf("can't open file palin.in\n",min);
   return;
 }
 fscanf(fp,"%s",slen);
 fscanf(fp,"%s",input);
 printf("%s   %s\n",slen,input);
 fclose(fp);
 getmin(0,input);
 printf("%d\n",min);
 fp=fopen("palin.out","w");
 if(fp==NULL)return;
 fprintf(fp,"%d\n",min);
 fclose(fp);
}

解决方案 »

  1.   

    The Center City fire department collaborates with the transportation 
    department to maintain maps of the city which reflects the current status of 
    the city streets. On any given day, several streets are closed for repairs or 
    construction.  Firefighters need to be able to select routes from the 
    firestations to fires that do not use closed streets.  
    Central City is divided into non-overlapping fire districts, each 
    containing a single firestation. When a fire is reported, a central dispatcher 
    alerts the firestation of the district where the fire is located and gives a 
    list of possible routes from the firestation to the fire. You must write a 
    program that the central dispatcher can use to generate routes from the 
    district firestations to the fires.Input and Output
    The city has a separate map for each fire district. Streetcorners of each 
    map are identified by positive integers less than 21, with the firestation 
    always on corner #1. The input file contains several test cases representing 
    different fires in different districts.  The first line of a test case 
    consists of a single integer which is the number of the streetcorner closest 
    to the fire. The next several lines consist of pairs of positive integers 
    separated by blanks which are the adjacent streetcorners of open streets. (For 
    example, if the pair 4 7 is on a line in the file, then the street between 
    streetcorners 4 and 7 is open. There are no other streetcorners between 4 and 
    7 on that section of the street.) The final line of each test case consists of 
    a pair of 0誷.
    For each test case, your output must identify the case by number (case #1, 
    case #2, etc). It must list each route on a separate line, with the 
    streetcorners written in the order in which they appear on the route. And it 
    must give the total number routes from firestation to the fire.  Include only 
    routes which do not pass through any streetcorner more than once.  (For 
    obvious reasons, the fire department doesn誸 want its trucks driving around in 
    circles.) Output from separate cases must appear on separate lines. The 
    following sample input and corresponding correct output represents two test 
    cases.  Sample Input    Sample Output6              CASE 1:
    1 2            1   2   3   4   6
    1 3            1   2   3   5   6
    3 4            1   2   4   3   5   6
    3 5            1   2   4   6
    4 6            1   3   2   4   6
    5 6            1   3   4   6
    2 3            1   3   5   6
    2 4            There are 7 routes from the firestation to streetcorner 6.
    0 0            CASE 2:
    4              1   3   2   5   7   8   9   6   4
    2 3            1   3   4
    3 4            1   5   2   3   4
    5 1            1   5   7   8   9   6   4
    1 6            1   6   4
    7 8            1   6   9   8   7   5   2   3   4
    8 9            1   8   7   5   2   3   4
    2 5            1   8   9   6   4
    5 7            There are 8 routes from the firestation to streetcorner 4.
    3 1
    1 8
    4 6
    6 9
    0 0
    ==============================================================================
      

  2.   

    回文算法: 我用的递归的方法, 测试过一些简单的输入,看起来好象比较正确:)
    不过我这是穷举, 搜索长串太慢了....
    #include <stdio.h>
    #include <string.h>int RoundStrCP(const char* str, int len, char* out)
    {
    if(len == 0)
    {
    return 0;
    }
    if(len == 1)
    {
    *out = *str;
    return 0;
    } char buf1[1024];  // &frac14;&Ugrave;&Eacute;è&acute;&reg;&sup3;¤&sup2;&raquo;&acute;ó&Oacute;&Uacute;1024&cedil;&ouml;×&Ouml;&frac12;&Uacute;
    char buf2[1024];  // &frac14;&Ugrave;&Eacute;è&acute;&reg;&sup3;¤&sup2;&raquo;&acute;ó&Oacute;&Uacute;1024&cedil;&ouml;×&Ouml;&frac12;&Uacute; if(str[0] == str[len-1])
    {
    *out = str[0];
    int ret = RoundStrCP(str+1, len-2, out+1);
    out[len+ret-1] = str[0];
    return ret;
    }
    int ra = RoundStrCP(str, len-1, buf1);
    int rb = RoundStrCP(str+1, len-1, buf2); if(ra<rb)
    {
    out[0] = str[len-1];
    strncpy(out+1, buf1, len-1+ra);
    out[len+ra] = str[len-1];
    return ra+1;
    }
    else
    {
    out[0] = str[0];
    strncpy(out+1, buf2, len-1+rb);
    out[len+rb]=str[0];
    return rb+1;
    }

    }int RoundStr(const char* str, char* out)
    {
    int len = strlen(str);
    int ret = RoundStrCP(str, len, out);
    out[len+ret] = 0;
    return ret;
    }int main(int argc, char** argv)
    {
    // const char* instr = "wwweriurwewwr";
    if(argc<2)
    {
    printf("&micro;÷&Oacute;&Atilde;·&frac12;&Ecirc;&frac12;:\nRoundStr <inputfilepath> [<outputfilepath>]\n\n"
    "inputfilepath   :  &Ecirc;&auml;&Egrave;&euml;&Icirc;&Auml;&frac14;&thorn;&Atilde;&ucirc;,&Icirc;&Auml;±&frac34;&cedil;&ntilde;&Ecirc;&frac12;,&Atilde;&iquest;&ETH;&ETH;&Ograve;&raquo;&Igrave;&otilde;&frac14;&Ccedil;&Acirc;&frac14;\n"
    "outputfilepath  :  &iquest;&Eacute;&Ntilde;&iexcl;,&Ecirc;&auml;&Egrave;&euml;&Icirc;&Auml;&frac14;&thorn;&Atilde;&ucirc;,&Icirc;&Auml;±&frac34;&cedil;&ntilde;&Ecirc;&frac12;,&Atilde;&iquest;&ETH;&ETH;&Ograve;&raquo;&Igrave;&otilde;&frac14;&Ccedil;&Acirc;&frac14;,&Egrave;&ccedil;&sup1;&ucirc;&Ecirc;&iexcl;&Acirc;&Ocirc;,&Ocirc;ò&Ecirc;&auml;&sup3;&ouml;&micro;&frac12;&iquest;&Oslash;&Ouml;&AElig;&Igrave;¨\n");
    return -1;
    } FILE *f_in = NULL;
    FILE *f_out = NULL; f_in=fopen(argv[1],"rt"); if(f_in==NULL)
    {
    printf("&acute;ò&iquest;&ordf;&Ecirc;&auml;&Egrave;&euml;&Icirc;&Auml;&frac14;&thorn;[%s]&Ecirc;§°&Uuml;!\n", argv[1]);
    return -1;
    } if(argc>2)
    {
    f_out = fopen(argv[2],"wt");
    if(f_out == NULL)
    {
    printf("&acute;ò&iquest;&ordf;&Ecirc;&auml;&sup3;&ouml;&Icirc;&Auml;&frac14;&thorn;[%s]&Ecirc;§°&Uuml;!&frac12;á&sup1;&ucirc;&frac12;&laquo;&acute;&Oacute;&iquest;&Oslash;&Ouml;&AElig;&Igrave;¨&Ecirc;&auml;&sup3;&ouml;\n", argv[2]);
    }
    } char  instr[1024];
    char  outstr[1024]; while (fscanf(f_in, "%[^\n]\n", instr) == 1)
    {
    if(instr[0] == 0) continue;
    int ret = RoundStr(instr, outstr); printf("&Ecirc;&auml;&Egrave;&euml;:%s\n&Ecirc;&auml;&sup3;&ouml;:%s\n&sup2;&aring;&Egrave;&euml;×&Ouml;·&ucirc;&Ecirc;&yacute;:%d\n\n",instr,outstr,ret); if(f_out)
    {
    fprintf(f_out, "&Ecirc;&auml;&Egrave;&euml;:%s\n&Ecirc;&auml;&sup3;&ouml;:%s\n&sup2;&aring;&Egrave;&euml;×&Ouml;·&ucirc;&Ecirc;&yacute;:%d\n\n",instr,outstr,ret);
    } } if(f_in) fclose(f_in);
    if(f_out) fclose(f_out);
    return 0;
    }
    输入:
    -------------------------------------
    qwertoiuyiorewsq
    1239873130951
    n,mxcz,mnzxc,zc
    weuryoiwreoiuweoruw
    kjdklfaljdsfl;adf;lasdljka
    ipousripoqorqowe[pqweqe
    []][]][699][][][][4][]
    mkioytvmniky
    7447723
    j3y66yj3
    hhytghyhh
    hgkjdghhkg输出:
    ---------------------------------------------------
    输入:qwertoiuyiorewsq
    输出:qswertoiuyuiotrewsq
    插入字符数:3输入:1239873130951
    输出:1235987031307895321
    插入字符数:6输入:n,mxcz,mnzxc,zc
    输出:n,mxcz,mnzxcxznm,zcxm,n
    插入字符数:8输入:weuryoiwreoiuweoruw
    输出:weuryoiwreoiuwuioerwioyruew
    插入字符数:8输入:kjdklfaljdsfl;adf;lasdljka
    输出:akjdklfaljdsfal;adfda;lafsdjlaflkdjka
    插入字符数:11输入:ipousripoqorqowe[pqweqe
    输出:ieqewqp[ewousqripoqopirqsuowe[pqweqei
    插入字符数:14输入:[]][]][699][][][][4][]
    输出:][]4[][][][6]99]6[][][][4][]
    插入字符数:6输入:mkioytvmniky
    输出:mykioytvmnmvtyoikym
    插入字符数:7输入:7447723
    输出:3277447723
    插入字符数:3输入:j3y66yj3
    输出:j3jy66yj3j
    插入字符数:2输入:hhytghyhh
    输出:hhytghgtyhh
    插入字符数:2输入:hgkjdghhkg
    输出:hgkjdghhgdjkgh
    插入字符数:4Press any key to continue
      

  3.   

    增加字典缓冲, 提高处理速度:
    呵呵,使用空间换时间..........#include <stdio.h>
    #include <string.h>
    #pragma warning(disable:4786)
    #include <map>
    #include <string>typedef std::map<std::string, std::string>  MAPSTR;int RoundStrCP(const char* str, int len, char* out, MAPSTR& dict)
    {
    if(len == 0)
    {
    return 0;
    }
    if(len == 1)
    {
    *out = *str;
    return 0;
    } MAPSTR::iterator it = dict.find(std::string(str, len));
    if(it != dict.end())
    {
    strncpy(out, it->second.c_str(), it->second.length());
    return it->second.length() - len;
    } char buf1[1024];  // &frac14;&Ugrave;&Eacute;è&acute;&reg;&sup3;¤&sup2;&raquo;&acute;ó&Oacute;&Uacute;1024&cedil;&ouml;×&Ouml;&frac12;&Uacute;
    char buf2[1024];  // &frac14;&Ugrave;&Eacute;è&acute;&reg;&sup3;¤&sup2;&raquo;&acute;ó&Oacute;&Uacute;1024&cedil;&ouml;×&Ouml;&frac12;&Uacute; if(str[0] == str[len-1])
    {
    *out = str[0];
    int ret = RoundStrCP(str+1, len-2, out+1, dict);
    out[len+ret-1] = str[0];
    dict[std::string(str, len)] = std::string(out, len+ret);
    return ret;
    }
    int ra = RoundStrCP(str, len-1, buf1, dict);
    int rb = RoundStrCP(str+1, len-1, buf2, dict); if(ra<rb)
    {
    out[0] = str[len-1];
    strncpy(out+1, buf1, len-1+ra);
    out[len+ra] = str[len-1];
    dict[std::string(str, len)] = std::string(out, len+ra+1);
    return ra+1;
    }
    else
    {
    out[0] = str[0];
    strncpy(out+1, buf2, len-1+rb);
    out[len+rb]=str[0];
    dict[std::string(str, len)] = std::string(out, len+rb+1);
    return rb+1;
    }
    }int RoundStr(const char* str, char* out)
    {
    MAPSTR   dict;
    int len = strlen(str);
    int ret = RoundStrCP(str, len, out, dict);
    out[len+ret] = 0;
    return ret;
    }int main(int argc, char** argv)
    {
        ... 省略...
    }