`

poj 3007

 
阅读更多

大致题意:

给定一个字符串,从任意位置把它切为两半,得到两条子串

定义 子串1为s1,子串2为s2,子串1的反串为s3,子串2的反串为s4

现在从s1 s2 s3 s4中任意取出两个串组合,问有多少种不同的组合方法

规定:

(1)       串Si不能和其 反串 组合

(2)       Si+Sj 与 Sj+Si 是两种组合方式(但未必是不同的组合方式)

 


思路:字符串ELFHash 哈希,针对本题来说就是把组合后的字符串转化为数字存起来,进行比较。

代码如下:

 

//题意:给定一个字符串,从任意位置把它切为两半,得到两个子串
//定义子串1为s1,子串2为s2,子串1的反串为s3,子串2的反串为s4
//现在从s1 s2 s3 s4中任意取出两个串组合,问有多少种不同的组合方法
//限制: (1) 串Si不能和其反串组合 (2) Si+Sj与Sj+Si是两种组合方式(但未必是不同的组合方式)

#include <iostream>        //字符串ELFHash 哈希
#include <algorithm>
#include<string>
using namespace std;
const int  M=10000;  //M=100000  MLE      M=100000   7972K 844MS        M=10000   928K 79MS

int len,res;
char table[10000][80],str[80],tmp[80];

int ELFHash(char a[80])        
{
    int h = 0;
    int x  = 0;
    for(int i=0;i<len;++i)
    {
        h = (h << 4) + (a[i]);
        if ((x = h & 0xF0000000L) != 0)
        {
            h ^= (x >> 24);
            h &= ~x;
        }
    }
    return h % M;
}

void insert(char a[])    //ELFHash函数对字符串判重
{
    int i=ELFHash(a);
    while(strlen(table[i])>0&&strcmp(a,table[i])!=0)
        i=(i+1)%M;
    if(strlen(table[i])==0)
    {
        strcpy(table[i],a);
        res++;
    }
}

int main()
{
    int t,i,j;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s",str);
        len=strlen(str);
        tmp[len]='\0';        
        res=0;
        for(i=0;i<M;++i)
            strcpy(table[i],"");
        insert(str);
        reverse(&str[0],&str[len]);
        insert(str);

        for(i=0;i<len-1;++i)        //( 0 i ),( i+1 len-1 ) 设原字符串拆分为两个子串 A,B,经重新组合变成 C,D
        {
            //前三个insert都是C对应A,D对应B,不应出现"正向 正向"的组合,因为这正是原字符串
            //后三个insert都是C对应B,D对应A,不应出现"反向 反向"的组合,因为这正是原字符串的翻转

            for(j=0;j<=i;++j)
                tmp[j]=str[j];
            for(j=i+1;j<len;++j)
				tmp[i+len-j]=str[j];
		
            insert(tmp);    //正向 反向    ,表示 A(!B) , (!B)意思是反向 

            for(j=0;j<=i;++j)
                tmp[i-j]=str[j];
            for(j=i+1;j<len;++j)
                tmp[j]=str[j];
            insert(tmp);    //反向 正向    ,表示 (!A)B

            for(j=0;j<=i;++j)
                tmp[i-j]=str[j];
            for(j=i+1;j<len;++j)
                tmp[i+len-j]=str[j];
            insert(tmp);    //反向 反向    ,表示 (!A)(!B)
            


            for(j=i+1;j<len;++j)
                tmp[j-i-1]=str[j];
            for(j=0;j<=i;++j)
                tmp[j+len-i-1]=str[j];
            insert(tmp);    //正向 正向    ,表示 BA
    
            for(j=i+1;j<len;++j)
                tmp[j-i-1]=str[j];
            for(j=0;j<=i;++j)
                tmp[len-1-j]=str[j];
            insert(tmp);    //正向 反向    ,表示 B(!A)
    
            for(j=i+1;j<len;++j)
                tmp[len-1-j]=str[j];
            for(j=0;j<=i;++j)
                tmp[j+len-i-1]=str[j];
            insert(tmp);    //反向 正向    ,表示 (!B)A
        
        }
        printf("%d\n",res);
    }
    return 0 ;
}

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics