蓝桥杯每日一题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;
}
相关推荐
HY小宝F40 分钟前
职场沟通的深层智慧:从对抗到协作的自我修炼
职场和发展
AI职业加油站2 小时前
职业提升之路:我的大数据分析师学习与备考分享
大数据·人工智能·经验分享·学习·职场和发展·数据分析
_OP_CHEN2 小时前
【算法基础篇】(五十六)容斥原理指南:从集合计数到算法实战,解决组合数学的 “重叠难题”!
算法·蓝桥杯·c/c++·组合数学·容斥原理·算法竞赛·acm/icpc
草履虫建模9 小时前
力扣算法 1768. 交替合并字符串
java·开发语言·算法·leetcode·职场和发展·idea·基础
学历真的很重要18 小时前
【系统架构师】第二章 操作系统知识 - 第二部分:进程管理(详解版)
学习·职场和发展·系统架构·系统架构师
VT.馒头20 小时前
【力扣】2722. 根据 ID 合并两个数组
javascript·算法·leetcode·职场和发展·typescript
执着25920 小时前
力扣hot100 - 108、将有序数组转换为二叉搜索树
算法·leetcode·职场和发展
LiLiYuan.21 小时前
【Cursor 中找不到LeetCode 插件解决办法】
算法·leetcode·职场和发展
南风知我意95721 小时前
【前端面试5】手写Function原型方法
前端·面试·职场和发展