2013年第四届蓝桥杯C/C++程序设计本科B组省赛题目汇总:
http://blog.youkuaiyun.com/u014552756/article/details/50576336
带分数
100 可以表示为带分数的形式:100 = 3 + 69258 / 714
还可以表示为:100 = 82 + 3546 / 197
注意特征:带分数中,数字1~9分别出现且只出现一次(不包含0)。
类似这样的带分数,100 有 11 种表示法。
题目要求:
从标准输入读入一个正整数N (N<1000*1000)
程序输出该数字用数码1~9不重复不遗漏地组成带分数表示的全部种数。
注意:不要求输出每个表示,只统计有多少表示法!
例如:
用户输入:
100
程序输出:
11
再例如:
用户输入:
105
程序输出:
6
资源约定:
峰值内存消耗 < 64M
CPU消耗 < 3000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。
所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
注意: main函数需要返回0
注意: 只使用ANSI C/ANSI C++ 标准,不要调用依赖于编译环境或操作系统的特殊函数。
注意: 所有依赖的函数必须明确地在源文件中 #include <xxx>, 不能通过工程设置而省略常用头文件。
提交时,注意选择所期望的编译器类型。
方法一:
思路:
我们可以把问题简化为下面的表达式:
num = left + up / down
我们的思想是:
先遍历left,再遍历down,两层for循环就可以解决;
找出符合条件(left、up、down为1~9不重复的9个数字组成)。
# inclde <stdio.h>
# include <string.h>
char flag[10];
char backup[10];
int check(int n)
{
do {
flag[n % 10]++;
} while(n /= 10);
if(flag[0] != 0) {
return 1;
}
for(int i = 1; i < 10; i++) {
if(flag[i] > 1) {
return 1;
}
}
return 0;
}
int checkAll(void)
{
for(int i = 1; i < 10; i++) {
if(flag[i] != 1) {
return 1;
}
}
return 0;
}
int main(void)
{
int num;
int count = 0;
scanf("%d", &num);
int left, right, up, down;
for(left = 1; left < num; left++) {
memset(flag, 0, 10);
if(check(left)) {
continue;
}
memcpy(backup, flag, 10);
for(down = 1; down < 100000; down++) {
memcpy(flag, backup, 10);
up = (num - left) * down;
if(check(down) || check(up)) {
continue;
}
if(! checkAll()) {
//printf("%d = %d + %d / %d\n", num, left, up, down);
count++;
}
}
}
printf("%d\n", count);
}
方法二:
#include<iostream>
#include<string.h>
using namespace std;
bool used[10];
int a[10], N, total;
void permutation(int pos){
if (pos == 9)
{
int p = 1, q = 9;//+、/位置
int x, y, z;//x+y/z==N?
for (p = 1; p < 9; p++)
{
x = 0;
for (int i = 1; i <= p; i++)
x = x * 10 + a[i];
if (x >= N)break;
for (q = 9; q>p; q--)
{
y = 0; z = 0;
for (int i = q; i <= 9; i++)
z = z * 10 + a[i];
for (int i = p + 1; i < q; i++)
y = y * 10 + a[i];
if (z>y)break;
if ((y%z==0)&&((x + y / z) == N))
total++;
}
}
return;
}
for (int i = 1; i < 10; i++){
if (!used[i]){
used[i] = true;
a[pos + 1] = i;
permutation(pos + 1);
used[i] = false;
}
}
}
int main()
{
cin >> N;
total = 0;
permutation(0);
cout << total << endl;
system("pause");
return 0;
}