蓝桥杯每日一题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;
}
相关推荐
xxxxxxllllllshi1 天前
Java中Elasticsearch完全指南:从零基础到实战应用
java·开发语言·elasticsearch·面试·职场和发展·jenkins
派大星爱吃猫1 天前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展
第七种黄昏2 天前
【前端高频面试题】深入浏览器渲染原理:从输入 URL 到页面绘制的完整流程解析
前端·面试·职场和发展
程序员杰哥2 天前
UI自动化测试实战:从入门到精通
自动化测试·软件测试·python·selenium·测试工具·ui·职场和发展
sprintzer2 天前
10.6-10.15力扣模拟刷题
算法·leetcode·职场和发展
测试19982 天前
Jmeter是如何实现接口关联的?
自动化测试·软件测试·python·测试工具·jmeter·职场和发展·接口测试
CoderYanger2 天前
前端基础——HTML练习项目:填写简历信息
前端·css·职场和发展·html
ProcessOn官方账号2 天前
深度解析产品运营的多元策略
程序人生·职场和发展·产品运营
红糖生姜2 天前
P12874 [蓝桥杯 2025 国 Python A] 巡逻||题解||图论
c++·蓝桥杯·图论
Espresso Macchiato2 天前
Leetcode 3715. Sum of Perfect Square Ancestors
算法·leetcode·职场和发展·leetcode hard·树的遍历·leetcode 3715·leetcode周赛471