码迷,mamicode.com
首页 > 其他好文 > 详细

Joke with permutation 搜索

时间:2015-08-01 18:35:21      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

                      Joke with permutation

题目抽象:对于1~n的排列,用空格将整数隔开。现在将空格哦去掉,成了一个没有空格的数字字符串。请将他还原,如有多个,输出任意一个即可。

分析:首先根据长度可以出去 n . 然后搜索。给DFS字符串位置参数。  对于每个位置的字符cur,可以自己组成一个整数,也可以和下一位组成一个整数。

没组成一个整数x,就将flag[x] = 1. 注意0只能在两位数的整数的各位。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cstring>
 5 #include <algorithm>
 6 #include <string>
 7 #include <vector>
 8 #include <set>
 9 #include <map>
10 #include <queue>
11 #include <stack>
12 using namespace std;
13 typedef long long LL;
14 const LL INF = 0x4fffffff;
15 const double EXP= 1e-5;
16 const LL MOD = 1e9+7;
17 const int MS= 105;
18 
19 bool flag[MS];
20 bool tag[MS];
21 char str[MS];
22 bool over;
23 int len,n;
24 
25 void dfs(int cur)
26 {
27     if(over)
28         return ;
29     if(cur >= len)
30     {
31         for(int i = 0 ;i < len; i++)
32         {
33                 printf("%c",str[i]);
34                 if(tag[i] == 1 && i != len -1 )
35                         printf(" ");
36         }
37         over = true;
38         return ;
39     }
40 
41     //  0只能在两位数的整数中的个位。这里保证下一次dfs中的cur位置不会是0.
42 
43     if(!flag[str[cur] - 0] && ( cur + 1 >= len || str[cur + 1] != 0))
44     {
45                 tag[cur] = 1;    // 这里表示在这个位置组成一个整数,便于确定空格的位置。
46                 flag[str[cur] - 0 ] = 1;
47                 dfs(cur + 1);
48                 tag[cur] = 0;                         //回退。
49                 flag[str[cur] - 0]  = 0;
50     }
51 
52     if(!flag[(str[cur] - 0) * 10 + str[cur + 1] - 0] && ((str[cur] - 0) * 10 + str[cur+1] -0) <= n && (cur + 2 >= len || str[cur + 2] != 0))
53     {
54                 tag[cur + 1] = 1;
55                 flag[(str[cur] - 0) * 10 + str[cur + 1] - 0] = 1;
56                 dfs(cur + 2);
57                 tag[cur + 1 ] = 0;
58                 flag[(str[cur] - 0) * 10 + str[cur + 1] - 0] = 0;
59     }
60 }
61 
62 
63 int main()
64 {
65     scanf("%s",str);
66     len = strlen(str);
67     if(len <= 9)
68     {
69         for(int i = 0; i < len; i++)
70         {
71                 if(i == 0)
72                     printf("%c",str[i]);
73                 else
74                     printf(" %c",str[i]);
75         }
76         return 0;
77     }
78     n = (len - 9) / 2 + 9;
79     over = false;
80     memset(flag,0,sizeof(flag));
81     memset(tag,0,sizeof(tag));
82     dfs(0);
83     return 0;
84 }

 

Joke with permutation 搜索

标签:

原文地址:http://www.cnblogs.com/hutaishi/p/4694313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!