蓝桥杯每日一题2023.11.19

题目描述

"蓝桥杯"练习系统 (lanqiao.cn)

题目分析

首先想到的方法为dfs去寻找每一个数,但发现会有超时

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int n, cnt, a[N];
void dfs(int dep, int sum, int start)
{
	if(dep == 4)
	{
		if(sum == 0 && cnt == 0)
		{
			for(int i = 0; i < 4; i ++)
			{
				cout << a[i] << ' ';
			}
			cnt ++;
		}
		return;
	}
	for(int i = start; i <= sqrt(sum); i ++)
	{
		a[dep] = i;
		dfs(dep + 1, sum - (i * i), i);
	} 
}
int main()
{
	cin >> n;
	dfs(0, n, 0);
	return 0;
}

使用二分

先将后两个数确定,将其后两个数的平方和以及分别对应的数字存入结构体中,再一一枚举前两个数,二分出可以匹配的后两个数,确定出答案

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N = 5e6 + 10;
int n, num;
struct node
{
	int ss, c, d;
}sum[N * 2];
bool cmp(node x, node y)
{
	if(x.ss != y.ss)
	{
		return x.ss < y.ss;	
	} 
	else
	{
		if(x.c != y.c)
		{
			return x.c < y.c;
		}
		else
		{
			return x.d < y.d;
		}
	}
}
int main()
{
	cin >> n;
	for(int c = 0; c * c <= n; c ++)
	{
		for(int d = c; c * c + d * d <= n; d ++)
		{
			sum[num ++] = {c * c + d * d, c, d};
		}
	}
	sort(sum, sum + num, cmp);
	for(int a = 0; a * a <= n; a ++)
	{
		for(int b = 0; a * a + b * b <= n; b ++)
		{
			int t = n - a * a - b * b;
			int l = 0, r = num - 1;
			while(l < r)
			{
				int mid = l + r >> 1;
				if(sum[mid].ss >= t)r = mid;
				else l = mid + 1;
			}
			if(sum[l].ss == t)
			{
				cout << a << ' ' << b << ' ' << sum[l].c << ' ' << sum[l]. d;
				return 0;
			}
			
		} 
	}
	return 0;
}
相关推荐
a程序小傲7 分钟前
京东Java面试被问:Fork/Join框架的使用场景
java·开发语言·后端·postgresql·面试·职场和发展
华清远见成都中心29 分钟前
嵌入式工程师技术面试有哪些注意事项?
面试·职场和发展
沐雪架构师33 分钟前
大模型Agent面试精选15题(第三辑)LangChain框架与Agent开发的高频面试题
面试·职场和发展
YoungHong19922 小时前
面试经典150题[074]:填充每个节点的下一个右侧节点指针 II(LeetCode 117)
leetcode·面试·职场和发展
元亓亓亓2 小时前
LeetCode热题100--763. 划分字母区间--中等
算法·leetcode·职场和发展
LYFlied3 小时前
【每日算法】LeetCode 70. 爬楼梯:从递归到动态规划的思维演进
算法·leetcode·面试·职场和发展·动态规划
YoungHong19923 小时前
面试经典150题[073]:从中序与后序遍历序列构造二叉树(LeetCode 106)
leetcode·面试·职场和发展
业精于勤的牙3 小时前
浅谈:算法中的斐波那契数(五)
算法·leetcode·职场和发展
regon3 小时前
第九章 述职11 交叉面试
面试·职场和发展·《打造卓越团队》
LYFlied3 小时前
【每日算法】LeetCode 105. 从前序与中序遍历序列构造二叉树
数据结构·算法·leetcode·面试·职场和发展