现在的位置: 首页 > 综合 > 正文

USACO Runaround Numbers

2018年05月02日 ⁄ 综合 ⁄ 共 2210字 ⁄ 字号 评论关闭

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




























题解
可以每一位都枚举,再判断(这里有点复杂);
/*
ID:CYMXYYM1
TASK:runround
LANG:C++
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
int a[13];bool f[13];bool s[10];
inline bool ok(int);
int main()
{
    freopen("runround.in","r",stdin);
    freopen("runround.out","w",stdout);
    int m,i,j;
    scanf("%d",&m);
    for (i=0;i<=12;i++) {a[i]=0;f[i]=true;}
    for (i=1;i<=9;i++) s[i]=true;
    i=0;
    while (m>0)
     {
       i++;
       a[i]=m%10;
       m/=10;
     }
    a[1]++;
    j=i;
   while (j>0)
    {
      int k=0; 
      for (k=a[j];k<=9;k++)
      if ((k%i!=0)&&(s[k]))
      {
       int l=(j-k%i+i)%i;
       if (l==0) l=i;
       if (f[l])              
        {
         a[j]=k;s[k]=false;
         j--;
         f[l]=false;
         break;
        }
       }
     if (k>=10) 
      {
         a[j]=1;
         j++;
         int l=(j-a[j]%i+i)%i;
         if (l==0) l=i;
         f[l]=true;s[a[j]]=true;
         a[j]++;
         if (j>i) i=j;
      }
     if ((j==0)&&(ok(i)))
         {
             j++;
             int l=(j-a[j]%i+i)%i;
             if (l==0) l=i;
             f[l]=true;s[a[j]]=true;
             a[j]++;
         }
    }
 for(int k=i;k>0;k--) printf("%d",a[k]);
 std::cout<<'\n';
}
bool ok(int x)
{
 int j=(x-a[x]%x+x)%x;
 int n=1;
 while (j!=0)
  {
    j=(j-a[j]%x+x)%x;
    n++;
    if (n>x) break;
  }
  return (n!=x);
}

抱歉!评论已关闭.