UVa 263 - Number Chains
阿新 • • 發佈:2017-06-03
end += node space uva scan initial pri art
題目:給你一個數字n0。將它的每一個位的數字按遞增排序生成數a,按遞減排序生成數b,
新的數字為n1 = a-b,下次依照相同方法計算n1,知道出現循環,問計算了多少次。
分析:數論、模擬。直接模擬計算就可以,利用hash表判重。
說明:註意初始化。
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cstdio> #include <cmath> using namespace std; //hash typedef struct hash_node { int path; hash_node* next; }hnode; hnode* tabel[1002]; hnode nodeh[1002]; int hash_size; void hash_initial() { memset(tabel, 0, sizeof(tabel)); hash_size = 0; } int hash_find(int s) { int v = s%1001; for (hnode* p = tabel[v] ; p ; p = p->next) if (p->path == s) return 1; nodeh[hash_size].next = tabel[v]; nodeh[hash_size].path = s; tabel[v] = &nodeh[hash_size ++]; return 0; } //hash end int buf[11]; int number(int *a, int n) { int value = 0; for (int i = 0 ; i < n ; ++ i) { value *= 10; value += a[i]; } return value; } int cmp1(int a, int b) { return a < b; } int cmp2(int a, int b) { return a > b; } int main() { int n,count,sum,a,b; while (~scanf("%d",&n) && n) { printf("Original number was %d\n",n); hash_initial(); sum = 0; do { hash_find(n); sum ++; count = 0; while (n) { buf[count ++] = n%10; n /= 10; } sort(buf, buf+count, cmp2); a = number(buf, count); sort(buf, buf+count, cmp1); b = number(buf, count); printf("%d - %d = %d\n",a,b,n = a-b); }while (!hash_find(n)); printf("Chain length %d\n\n",sum); } return 0; }
UVa 263 - Number Chains