2013年第四届蓝桥杯B组C++省赛I题

2013年第四届蓝桥杯B组C++省赛I题

带分数

100 可以表示为带分数的形式:100 = 3 + 69258 / 714

还可以表示为:100 = 82 + 3546 / 197

注意特征:带分数中,数字1~9分别出现且只出现一次(不包含0)。

类似这样的带分数,100 有 11 种表示法。

题目要求:
从标准输入读入一个正整数N (N<1000*1000)
程序输出该数字用数码1~9不重复不遗漏地组成带分数表示的全部种数。
注意:不要求输出每个表示,只统计有多少表示法!

例如:
用户输入:
100
程序输出:
11

再例如:
用户输入:
105
程序输出:
6

传送门

呃。。这道题我用next_permutation()写的。。。测了一下大数。。预测会超时。结果发现蓝桥杯官网上面有这道题。。。呃。。提交了一下。。没超。。。但是有点危险。打算用dfs做下
反正都差不多。

组合排列方法

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

int a[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int n;
int ans;

int number(int i, int j)
{
	int ans = 0;
	for (int k = i; k <= j; k++)
	{
		ans = ans * 10 + a[k];
	}
	return ans;
}

int main()
{
	cin >> n;
	do
	{
		for (int i = 1; i < 7; i++)
		{
			int aa = number(1, i);
			if (aa >= n)
			{
				break;
			}
			for (int j = i + 1; j < 9; j++)
			{
				int b = number(i + 1, j);
				int c = number(j + 1, 9);
				if (b < c)
				{
					continue;
				}
				if (!(b % c) && (aa + b / c == n))
				{
					ans++;
				}
			}
		}
	}while (next_permutation(a + 1, a + 10));
	cout << ans << endl;
	return 0;
}

dfs代码:

扫描二维码关注公众号,回复: 9664518 查看本文章
#include <bits/stdc++.h>
using namespace std;

int a[12];
int vis[10];
int n;
int ans;

int number(int i, int j)
{
	int ans = 0;
	for (int k = i; k <= j; k++)
	{
		ans = ans * 10 + a[k];
	}
	return ans;
}

void dfs(int s)
{
	if (s == 9)
	{
		for (int i = 0; i < 6; i++)
		{
			int aa = number(0, i);
			if (aa > n)
			{
				break;
			}
			for (int j = i + 1; j < 8; j++)
			{
				int b = number(i + 1, j);
				int c = number(j + 1, 8);
				if (b < c)
				{
					continue;
				}
				if (!(b % c) && (aa + b / c == n))
				{
					ans++;
				}
			}
		}
		return ;
	}
	for (int i = 1; i <= 9; i++)
	{
		if (!vis[i])
		{
			vis[i] = 1;
			a[s] = i;
			dfs(s + 1);
			vis[i] = 0;
		}
	} 
}

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

呃呃呃。两个代码的处理时间相同。。。。呃呃呃。。

发布了60 篇原创文章 · 获赞 2 · 访问量 1606

猜你喜欢

转载自blog.csdn.net/qq_44624316/article/details/104723801