蓝桥杯2013年第四届真题-带分数(朴素dfs+优化)

 WA代码

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 20;

int n,m,res = 0,a,b;
bool st[N];
void dfs(int x)
{
	int tmp = m;
	while (tmp)
	{
		st[tmp % 10] = true;
		tmp /= 10;
	}
	if (x > 4)
	{
		for (int i = 1; i <= 9; i++)
		{
			if (!st[i]) 
				b = b * 10 + i;
		}


		if ((n - m)*a == b   &&!st[b] && !st[a])
			res++;

			a = 0,b = 0;
		return;
	}
	for (int i = 1; i <= 9; i++)
	{
		if (!st[i])
		{
			st[i] = true;
			a = a * 10 + i;
			dfs(x + 1);
			a -= i;
			st[i] = false;
		}
	}
}
int main()
{
	cin >> n;
	for (int i = 1; i < n; i++)
	{
		m = n - i;
		dfs(1);
	}
	cout << res << endl;
	return 0;
}

AC代码

思路:枚举全排列
           枚举位数,插版法 a|b|c
           计算   n  = a + b/c


//枚举全排列
//枚举位数,插版法 a|b|c
//计算


#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 1000010;

int n, m, res = 0, a, b;
bool st[N];
int arr[N];

int clac(int l, int r)
{
	int sum = 0;
	for (int i = l; i <= r; i++)
		sum = sum * 10 + arr[i];
	return sum;
}

void dfs(int x)
{

	if (x > 9)
	{
		for (int i = 1;i <= 7;i++)
			for (int j = i + 1; j <= 8; j++)
			{
				int a = clac(1, i);
				int b = clac(i + 1, j);
				int c = clac(j + 1, 9);
				if (c * n == a * c + b) res++;
			}
		return;
	}
	for (int i = 1; i <= 9; i++)
	{
		if (!st[i])
		{
			arr[x] = i;
			st[i] = true;
			dfs(x + 1);
			st[i] = false;
		}
	}
}

int main()
{
	cin >> n;
	dfs(1);
	cout << res << endl;
	return 0;
}

优化

枚举a,对于每一个a枚举c,对于每一个a,c算b是否合法

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 20;

int n,  res = 0;
bool st[N];
bool backup[N];


bool check(int a, int c)
{
	long long b = (long long)c * n - a * c;
	if (!a || !c || !b)  return false;
	memcpy(backup, st, sizeof st);
	while (b)
	{
		int x = b % 10;
		b /= 10;
		if (!x || backup[x]) return false;
		backup[x] = true;
	}
	for (int i = 1; i <= 9; i++)
		if (!backup[i]) return false;

	return true;
}

void dfs_c(int x, int a, int c)
{
	if (x >= 9) return;

	if (check(a, c)) res++;

	for (int i = 1; i <= 9; i++)
	{
		if (!st[i])
		{
			st[i] = true;
			dfs_c(x + 1, a, c * 10 + i);
			st[i] = false;
		}
	}
}

void dfs_a(int x, int a)
{
	if (a >= n) return;
	if (a)  dfs_c(x, a, 0);

	for (int i = 1; i <= 9; i++)
	{
		if (!st[i])
		{
			st[i] = true;
			dfs_a(x + 1, a * 10 + i);
			st[i] = false;
		}
	}
}

int main()
{
	cin >> n;
	dfs_a(0, 0);
	cout << res << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值