蓝桥杯每日一题2023.9.30

蓝桥杯大赛历届真题 - C&C++ 大学 B 组 - 蓝桥云课 (lanqiao.cn)

题目描述

题目分析

对于此题,首先想到了dfs进行一一找寻,注意每次不要将重复的算进去,故我们每次循环可以记录一个开始的位置,下一次到这个位置时,这个数就不会被重复选择

没有运行出来的代码:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long  ull;
const int N = 2e5 + 10;
ull ans, a[N];
void dfs(int n, ull start)
{
	if(n == 3) 
	{
		ull sum = a[0];
		for(int i = 1; i < 3; i ++)sum *= a[i];
		if(sum == 2021041820210418)ans ++;
		return;
	}
	for(ull i = start; i <= 2021041820210418; i ++)
	{
		a[n] = i;
		dfs(n + 1, i);
		a[n] = 0;
	}
}
int main()
{
	dfs(0, 1);
	cout << ans;
	return 0;
}

发现数字过大,运行时间过长,思考如何进行优化,想到这三个数都是2021041820210418的因数(这三个数乘积为2021041820210418),故我们可以先将2021041820210418的所有因数找出来,在这些因数中进行dfs

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
typedef unsigned long long ull;
ull cnt, a[N], q[N], ans;
void dfs(int dep, ull start)
{
	if(dep == 3)
	{
		ull sum = q[0];
		for(int i = 1; i < 3; i ++)sum *= q[i];
		if(sum == 2021041820210418)
		{
			ans ++;
		}
		return;
	}
	for(ull i = 0; i < cnt; i ++)
	{
		q[dep] = a[i];
		dfs(dep + 1, i);
		q[dep] = 0;
	}
}
int main()
{
	for(ull i = 1; i <= 2021041820210418 / i; i ++)
	{
		if(2021041820210418 % i)continue;
		a[cnt ++] = i;
		if(i != 2021041820210418 / i)a[cnt ++] = 2021041820210418 / i;
	}
	dfs(0, 0);
	cout << ans;
	return 0;
}

得到正解2430

当然也可以一进行纯纯暴力

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
typedef unsigned long long ull;
ull cnt, a[N], q[N], ans;
int main()
{
	for(ull i = 1; i <= 2021041820210418 / i; i ++)
	{
		if(2021041820210418 % i)continue;
		a[cnt ++] = i;
		if(i != 2021041820210418 / i)a[cnt ++] = 2021041820210418 / i;
	}
	for(int i = 0; i < cnt; i ++)
	{
		for(int j = 0; j < cnt; j ++)
		{
			for(int k = 0; k < cnt; k ++)
			{
				if(a[i] * a[j] * a[k] == 2021041820210418)ans ++;
			}
		}
	}
	cout << ans;
	return 0;
}
相关推荐
Miraitowa_cheems1 小时前
LeetCode算法日记 - Day 68: 猜数字大小II、矩阵中的最长递增路径
数据结构·算法·leetcode·职场和发展·贪心算法·矩阵·深度优先
测试老哥5 小时前
如何编写好测试用例?
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
爱学习的小鱼gogo16 小时前
python 矩阵中寻找就接近的目标值 (矩阵-中等)含源码(八)
开发语言·经验分享·python·算法·职场和发展·矩阵
代码对我眨眼睛1 天前
226. 翻转二叉树 LeetCode 热题 HOT 100
算法·leetcode·职场和发展
黑色的山岗在沉睡1 天前
LeetCode 494. 目标和
算法·leetcode·职场和发展
莫叫石榴姐1 天前
SQL百题斩:从入门到精通,一站式解锁数据世界
大数据·数据仓库·sql·面试·职场和发展
你总是一副不开心的样子(´ . .̫ .1 天前
一、十天速通Java面试(第三天)
java·面试·职场和发展·java面试
小欣加油1 天前
leetcode 62 不同路径
c++·算法·leetcode·职场和发展
夏鹏今天学习了吗1 天前
【LeetCode热题100(38/100)】翻转二叉树
算法·leetcode·职场和发展
夏鹏今天学习了吗1 天前
【LeetCode热题100(36/100)】二叉树的中序遍历
算法·leetcode·职场和发展