USACO 2.2 Runaround Numbers(乱搞)

效率好低,先DFS预处理所有的数,100万个左右,然后二分找到比n大的,然后枚举判断。

 1 /*

 2  ID: cuizhe

 3  LANG: C++

 4  TASK: runround

 5  */

 6 #include <iostream>

 7 #include <cstdio>

 8 #include <cstring>

 9 #include <cstdlib>

10 #include <map>

11 #include <algorithm>

12 #include <ctime>

13 using namespace std;

14 long long p[1000000];

15 int num,o[11];

16 void dfs(long long sum)

17 {

18     int i,z;

19     if(sum != 0)

20     p[num++] = sum;

21     z = 0;

22     for(i = 1;i <= 9;i ++)

23     {

24         if(!o[i])

25         {

26             o[i] = 1;

27             dfs(sum*10+i);

28             o[i] = 0;

29             z = 1;

30         }

31     }

32     if(!z) return ;

33 }

34 int judge(long long n)

35 {

36     int key[13],len,mm[13],ti,i,ll[13];

37     memset(mm,0,sizeof(mm));

38     len = 1;

39     while(n)

40     {

41         key[len++] = n%10;

42         n = n/10;

43     }

44     for(i = 1;i <= len-1;i ++)

45     ll[i] = key[len-i];

46     ti = 1;mm[1] = 1;

47     for(i = 2;i <= len-1;i ++)

48     {

49         ti = (ll[ti]+ti)%(len-1);

50         if(ti == 0)

51         ti = len-1;

52         mm[ti] ++;

53         if(mm[ti] >= 2)

54         return 0;

55     }

56     ti = (ll[ti]+ti)%(len-1);

57     if(ti == 1)

58     return 1;

59     else

60     return 0;

61 }

62 int main()

63 {

64     long long n,str,end,mid;

65     int i;

66     num = 1;

67     freopen("runround.in","r",stdin);

68     freopen("runround.out","w",stdout);

69     dfs(0);

70     sort(p+1,p+num);

71     scanf("%lld",&n);

72     str = 1;

73     end = num-1;

74     while(str < end)

75     {

76         mid = (str+end)/2;

77         if(p[mid] < n)

78         str = mid+1;

79         else

80         end = mid;

81     }

82     if(p[str] == n)

83     str ++;

84     for(i = str;i <= num-1;i ++)

85     {

86         if(judge(p[i]))

87         {

88             printf("%lld\n",p[i]);

89             break;

90         }

91     }

92     return 0;

93 }

 

你可能感兴趣的:(number)