UVA - 725:Division

Division

来源:UVA

标签:

参考资料:

相似题目:

题目

Write a program that finds and displays all pairs of 5-digit numbers that between them use the digits 0 through 9 once each, such that the first number divided by the second is equal to an integerN , where 2 N 79. That is,
abcde/fghij=N
where each letter represents a different digit. The first digit of one of the numerals is allowed to be zero.

输入

Each line of the input file consists of a valid integerN . An input of zero is to terminate the program.

输出

Your program have to display ALL qualifying pairs of numerals, sorted by increasing numerator (and, of course, denominator).
Your output should be in the following general form:
xxxxx / xxxxx = N
xxxxx / xxxxx = N

In case there are no pairs of numerals satisfying the condition, you must write ‘There are no solutions forN .’. Separate the output for two different values of N by a blank line.

输入样例

61
62
0

输出样例

There are no solutions for 61.

79546 / 01283 = 62
94736 / 01528 = 62

参考代码1

#include
#include
int arr[10];//0~9
int n,div,dived;
bool solution;
bool judge(int num)
{
	if(num>98765)return false;
	int temp[10];
	memcpy(temp,arr,sizeof(arr));
	while(num>0)
	{
		temp[num%10]++;
		num/=10;
	}
	for(int i=0;i<10;i++)
		if(temp[i]!=1)return false;
	return true;
}

void get_digit(int cnt)
{
	if(cnt==0)
	{
		dived=n*div;
		if(judge(dived)==true)
		{
			solution=true;
			printf("%5d / %05d = %d\n",dived,div,n);
		}
		return;
	}
	for(int i=0;i<=9;i++)
	{
		if(arr[i]==0)
		{
			arr[i]=1;
			cnt--;
			div=div*10+i;
			
			get_digit(cnt);
			
			arr[i]=0;
			cnt++;
			div=(div-i)/10;
		}
	}
}

int main()
{
	int kase=0;
	while(scanf("%d",&n)==1 && n)
	{
		if(kase++)printf("\n");//要求两个n间有一个空行。 
		div=dived=0;
		solution=false;
		memset(arr,0,sizeof(arr));
		get_digit(5);
		if(solution==false)printf("There are no solutions for %d.\n",n);
	}
	return 0;
}

####参考代码2

#include
#include
int arr[10];//0~9

void part_digit(int num)
{
	while(num>0)
	{
		arr[num%10]++;
		num/=10;
	}
}

bool judge()
{
	for(int i=0;i<10;i++)
		if(arr[i]!=1)return false;
	return true;
}

int main()
{
	int n;
	int kase=0;
	while(scanf("%d",&n)==1 && n)
	{
		if(kase++)printf("\n");//要求两个n间有一个空行。 
		int div,dived;
		bool solution=false;
		for(div=1234;div<98765;div++)
		{
			dived=div*n;
			if(dived>98765)break;
			
			memset(arr,0,sizeof(arr));
			if(div<10000)arr[0]++;
			part_digit(div);
			part_digit(dived);
			if(judge())
			{
				solution=true;
				printf("%05d / %05d = %d\n",dived,div,n);
			}
		} 
		if(solution==false)printf("There are no solutions for %d.\n",n);
	}
	return 0;
}

你可能感兴趣的:(【记录】算法题解)