TheLuckyString (SRM 428 Div2 500)


回溯生成所有的LuckyString,计数即可。10!*26操作数。在tc上不会超时。
看Summary中很多人用next_permutation生成所有全排列再判断是否为LuckyString,这样更快更方便一些。


   class TheLuckyString
              { 
              
public
                  
int len;
                  
int res;
                  
int cnt[26];
                  
int last;
                  
int visited[11];
              
int count(string s) 
                  {                         
                        memset(cnt,
0,sizeof(cnt));

                        len 
= s.size();
                        res 
= 0;

                        
for(int i=0;i<s.size();++i)
                            cnt[s[i]
-'a']++;

                        
int len = s.size();

                        bt();

                        
return res;

                        
return 0;
                  } 

              
void bt(){
                  
for(int i=0;i<26;++i){
                      
if(cnt[i]!=0){
                          visited[
0]=i;
                          cnt[i]
--;
                          _bt(
1);
                          cnt[i]
++;
                      }
                  }
              }

              
void _bt(int depth){
                  
if(depth==len){
                    res
++;
                    
return;
                  }                  
                      
for(int i=0;i<26;++i){
                          
if(cnt[i]!=0){
                              
if(i==visited[depth-1])
                                  
continue;
                            visited[depth] 
= i;
                            cnt[i]
--;
                            _bt(depth
+1);
                            cnt[i]
++;
                          }
                      }
              }


next_permutation解:

   class TheLuckyString
              { 
              
public
              
int count(string s) 
                  {                         

                  
int res = 0;

                  sort(s.begin(),s.end());

                  
do{
                      
bool ok = true;
                      
for(int i=0;i+1<s.size();++i){
                          
if(s[i]==s[i+1]){
                              ok 
= false;
                              
break;
                          }
                      }
                      
                      
if(ok)
                        res
++;

                  }
while( next_permutation(s.begin(),s.end()) );

                    
return res;
                  }
              }

posted on 2009-06-21 11:35 YZY 阅读(1012) 评论(0)  编辑 收藏 引用 所属分类: AlgorithmTopCoder


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


导航

<2009年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

统计

常用链接

留言簿(2)

随笔分类

随笔档案

搜索

积分与排名

最新评论

阅读排行榜