相乘后数字不变DFS

相乘后数字不变

Time Limit : 3000/1000ms (Java/Other)   Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 41   Accepted Submission(s) : 21
Font: Times New Roman | Verdana | Georgia
Font Size: ← →

Problem Description

由4个不同的数字,组成的一个乘法算式,它们的乘积仍然由这4个数字组成。
比如: 
210 x 6 = 1260 
8 x 473 = 3784
27 x 81 = 2187 
都符合要求。
如果满足乘法交换律的算式算作同一种情况,那么,包含上边已列出的3种情况,一共有多少种满足要求的算式。
请填写该数字,通过浏览器提交答案,不要填写多余内容(例如:列出所有算式)。

Input

Output

输出一个整数

Author

njtechliubin


这是一道普通的穷举题目,可是WA2次,好气。第一次是因为首位是0没有考虑,第二次是因为满足交换律算作一种情况,伤心。

思路本来是想算式一个函数,结果一个函数,之后函数传出一个数组给算式的函数结果,但是C++遗忘严重,忘记怎么写传数组的函数了,只能

写了一个全局数组。

#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int ans = 0;
int shuzi[4];
int vis[10];	
int vvis[4];
int hehe[30];
int cnt;
void chengji(int num[],int n,int he) {
	if (n == 4) {
		hehe[cnt++] = he;
		return;
	}
	for (int i = 0; i < 4; i++) {
		if (!vvis[i]) {
			vvis[i] = 1;
			chengji(num, n + 1, he + pow(10,(n))*num[i]);
			vvis[i] = 0;
		}
	}
}
void dfs(int n) {
	if (n == 4) {
		int x1 = shuzi[0] * 100 + shuzi[1] * 10 + shuzi[2];
		int y1 = shuzi[3];
		int x2 = shuzi[0] * 10 + shuzi[1];
		int y2 = shuzi[2] * 10 + shuzi[3];
		int x3 = shuzi[0];
		int y3 = shuzi[1] * 100 + shuzi[2] * 10 + shuzi[3];
		cnt = 0;  //init
		memset(hehe, 0, sizeof(hehe)); //init
		chengji(shuzi, 0, 0);
		for (int i = 0; i < 24; i++) {
			if (hehe[i] < 1000)continue;
			if (hehe[i] == x1*y1&&shuzi[0]!=0&&shuzi[3]!=0) {
				ans++;
		//		cout << x1 << ' ' << y1<<' ' << hehe[i] << endl;
			}
			if (hehe[i] == x2*y2&&shuzi[0] != 0 && shuzi[2] != 0) {
				ans++;
		//		cout << x2 << ' ' << y2 << ' ' << hehe[i] << endl;
			}
			if (hehe[i] == x3*y3&&shuzi[0] != 0 && shuzi[1] != 0) {
				ans++;
		//		cout << x3<< ' ' << y3 << ' ' << hehe[i] << endl;
			}
		}
		return;
	}
	for (int i = 0; i < 10; i++) {
		if (!vis[i]) {
			vis[i] = 1;
			shuzi[n] = i;
			dfs(n + 1);
			shuzi[n] = 0;
			vis[i] = 0;
		}
	}
}
int main()
{
	dfs(0);
	cout <<ans;
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值