习题2-6 排列 算法竞赛入门经典(C/C++)

用1-9九个数字组成三个三位数abc, def, ghi,每个数字恰好使用一次

要求三个数abc:def:ghi = 1 : 2 : 3的所有可能。按照“abc def ghi”格式输出所有解,一行为一个解。样例输出:192 384 576。

数据量级不大,直接暴力求解,每三层循环生成一个abc样的数字:

for(int i =1;i<10;i++){

		for(int j=1;j<10;j++){
			
            if(i==j){

				continue;
			}
			for(int t=1;t<10;t++){

				if(t==j||t==i)
				{
					continue;
				}
				a=i*100+j*10+t;    //“abc"样的数字
            }
        }
}

当然,每次循环要加上判断条件,有相同数字出现时直接进入下次循环。最终判断三个数字是否有1:2:3关系即可,完整代

#include <bits/stdc++.h>
using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
	
	int a=0,b=0,c=0;
	for(int i =1;i<4;i++)
	{
		for(int j=1;j<10;j++)
		{
			if(i==j)
			{
				continue;
			}
			for(int t=1;t<10;t++)
			{
				if(t==j||t==i)
				{
					continue;
				}
				a=i*100+j*10+t;
				for(int k =1;k<9;k++)
				{
					if(k==i||k==j||k==t)
					{
						continue;
					}
					for(int m=1;m<10;m++)
					{
						if(k==m||m==i||m==j||m==t)
						{
							continue;
						}
						for(int n=1;n<10;n++)
						{
							if(n==m||n==k||n==i||n==j||n==t)
							{
								continue;
							}
							b=k*100+m*10+n;
							for(int u =1;u<9;u++)
							{
								if(u==i||u==j||u==t)
								{
									continue;
								}
								for(int p=1;p<10;p++)
								{
									if(u==p||p==i||p==j||p==t||p==m||p==n||p==k)
									{
										continue;
									}
									for(int q=1;q<10;q++)
									{
										if(q==p||q==u||q==i||q==j||q==t||q==m||q==n||q==k)
										{
											continue;
										}
										c=u*100+p*10+q;
										if(b==a*2&&c==3*a)
										printf("%d %d %d\n",a,b,c);
										
									}
								}
							}
							
						}
					}
				}
				
			}
		}
	} 	
	system("pause");
	return 0;
}

码如下:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值