USACO Section 2.2 Runaround Numbers

Runaround Numbers

Runaround numbers are integers with unique digits, none of which is zero (e.g., 81362) that also have an interesting property, exemplified by this demonstration:

  • If you start at the left digit (8 in our number) and count that number of digits to the right (wrapping back to the first digit when no digits on the right are available), you'll end up at a new digit (a number which does not end up at a new digit is not a Runaround Number). Consider: 8 1 3 6 2 which cycles through eight digits: 1 3 6 2 8 1 3 6 so the next digit is 6.
  • Repeat this cycle (this time for the six counts designed by the `6') and you should end on a new digit: 2 8 1 3 6 2, namely 2.
  • Repeat again (two digits this time): 8 1
  • Continue again (one digit this time): 3
  • One more time: 6 2 8 and you have ended up back where you started, after touching each digit once. If you don't end up back where you started after touching each digit once, your number is not a Runaround number.

Given a number M (that has anywhere from 1 through 9 digits), find and print the next runaround number higher than M, which will always fit into an unsigned long integer for the given test data.

PROGRAM NAME: runround

INPUT FORMAT

A single line with a single integer, M

SAMPLE INPUT (file runround.in)

81361

OUTPUT FORMAT

A single line containing the next runaround number higher than the input value, M.

SAMPLE OUTPUT (file runround.out)

81362

题意:给你一个数 n 找出一个大于 n 的最小一个符合条件的数,这个数每位都不一样,而且要满足条件……
分析:直接暴力枚举。
View Code
 1 /*
 2   ID: dizzy_l1
 3   LANG: C++
 4   TASK: runround
 5 */
 6 #include<iostream>
 7 #include<cstring>
 8 #include<cstdio>
 9 #include<algorithm>
10 
11 using namespace std;
12 
13 void itoa(int a,char *str)
14 {
15     int t,i=0,j;
16     while(a)
17     {
18         t=a%10;a=a/10;
19         str[i++]=t+'0';
20     }
21     str[i]='\0';
22     j=i-1;i=0;
23     while(i<j)swap(str[i++],str[j--]);
24 }
25 
26 bool judge(int a)
27 {
28     int len,i,p;
29     char str[10];
30     bool visited[10];
31     itoa(a,str);
32     len=strlen(str);
33     memset(visited,false,sizeof(visited));
34     p=0;
35     while(!visited[p])
36     {
37         visited[p]=true;
38         p=(p+str[p]-'0')%len;
39     }
40     if(p) return false;
41     for(i=0;i<len;i++)
42         if(!visited[i])
43             return false;
44     sort(str,str+len);
45     for(i=0;i<len-1;i++)
46         if(str[i]==str[i+1])
47                 return false;
48     return true;
49 }
50 
51 int main()
52 {
53     freopen("runround.in","r",stdin);
54     freopen("runround.out","w",stdout);
55     int n,i;
56     while(scanf("%d",&n)==1)
57     {
58         for(i=n+1;!judge(i);i++);
59         printf("%d\n",i);
60     }
61     return 0;
62 }
posted @ 2012-09-01 11:21  mtry  阅读(301)  评论(0编辑  收藏  举报