USACO Runaround Numbers

来源:互联网 发布:求最短路径的算法 编辑:程序博客网 时间:2024/05/16 09:16

runaround numbers 肯定不包含0,数字不重复

两个技巧
把一个int 型整数按数字存入 char 数组, 然后将char 数组 改变为int 数组——sprintf函数

sprintf(numstr, "%d", n);size = strlen(numstr);for(i = 0; i < size; i++) {numdig[i] = numstr[i] - 48;}

检验数字是否run around 时,注意每次检验开始的点index
//whether Runaroundint times = size;int index = 0;while(times) {index = (index + numdig[index]) % size;visited[index] = true;times--;}for(j = 0; j < size; j++) {if(!visited[j]) return false;}

我的代码
/*ID: wangxin12PROG: runroundLANG: C++*/#include <iostream>#include <fstream>#include <vector>#include <string.h>#include <stack>using namespace std;int N;bool isRunaround(int n);int main() {//inputifstream fin("runround.in");fin>>N;fin.close();//int n = N + 1;while(!isRunaround(n)) {n++;}//bool n = isRunaround(147);//Outputofstream fout("runround.out");fout<<n<<endl;fout.close();return 0;}bool isRunaround(int n) {char numstr[10];int numdig[10];bool visited[10] = { false };int size, i, j;sprintf(numstr, "%d", n);size = strlen(numstr);for(i = 0; i < size; i++) {numdig[i] = numstr[i] - 48;}//有重复数字不算for(i = 0; i < size - 1; i++) {for(j = i + 1; j < size; j++) {if(numstr[i] == '0' || numstr[j] == '0' || numstr[i] == numstr[j])  return false;}}//whether Runaroundint times = size;int index = 0;while(times) {index = (index + numdig[index]) % size;visited[index] = true;times--;}for(j = 0; j < size; j++) {if(!visited[j]) return false;}return true;}



原创粉丝点击