UVa 263 - Number Chains

Posted llguanli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVa 263 - Number Chains相关的知识,希望对你有一定的参考价值。

题目:给你一个数字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的主要内容,如果未能解决你的问题,请参考以下文章

UVa 818Cutting Chains (暴力dfs+位运算+二进制法)

UVA818-Cutting Chains(二进制枚举+dfs判环)

UVA 818 Cutting Chains

UVA529 Addition Chains

UVA529 Addition Chains

UVa 818 Cutting Chains 题解