蓝桥杯每日一题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;
}
相关推荐
qq_459234425 天前
【题库】| 商用密码应用安全性评估从业人员考核题库(四十)
职场和发展·密码学·学习方法·考核·商用密码·商用密码应用安全性评估·密评
敲敲了个代码5 天前
[特殊字符] 空数组的迷惑行为:为什么 every 为真,some 为假?
前端·javascript·react.js·面试·职场和发展
诚思报告YH5 天前
视频面试软件市场洞察:2026 - 2032年复合年均增长率(CAGR)为10.3%
面试·职场和发展
重生之后端学习5 天前
74. 搜索二维矩阵
开发语言·数据结构·算法·职场和发展·深度优先
tyb3333335 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
Pitiless-invader5 天前
MySQL 相关知识及面试问题汇总
面试·职场和发展
重生之后端学习5 天前
35. 搜索插入位置
java·数据结构·算法·leetcode·职场和发展·深度优先
逆境不可逃6 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
筱昕~呀6 天前
冲刺蓝桥杯-DFS板块(第二天)
算法·蓝桥杯·深度优先
zheshiyangyang6 天前
前端面试基础知识整理【Day-10】
前端·面试·职场和发展