BestCoder Round #61 HDOJ5522 5523 5524题解

本文探讨了通过直接暴力枚举、二分查找等方法解决算法问题的优化策略,并介绍了如何利用C++ STL库中的lower_bound函数提升效率。此外,还详细解释了针对特定条件的代码实现,如在不同场景下输出YES、NO或特定数值,以及解决完全二叉树相关问题的方法。文章旨在提供算法优化和数据结构应用的实用指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: 点击打开链接


A: 直接无脑暴力枚举三个数, 或者枚举前两个数, 第三个数二分, 我用了stl的lower_bound()

AC代码:

#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 105;
int n, a[MAXN];
int main(int argc, char const *argv[])
{
    while(scanf("%d", &n) != EOF) {
        bool flag = false;
        for(int i = 1; i <= n; ++i)
            scanf("%d", &a[i]);
        sort(a + 1, a + n + 1);
        for(int i = 1; i <= n - 2; ++i) {
            for(int j = i + 1; j <= n - 1; ++j) {
                int x = a[i] + a[j];
                int *pos = lower_bound(a + j + 1, a + n + 1, x);
                if(*pos == x) {
                    flag = true;
                    printf("YES\n");
                    break;
                }                
            }
            if(flag) break;
        }
        if(!flag) printf("NO\n");
    }
    return 0;
}


B: 分析后对变量分类讨论即可, n为1或起点与终点在两端则ans为0, 起点与终点重合则ans为-1, 起点与终点相邻或起点在两端ans为1, 

其他情况ans为2.

AC代码:

#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 1e4;
int n, s, t;
int main(int argc, char const *argv[])
{
	while(scanf("%d", &n) != EOF) {
		scanf("%d%d", &s, &t);
		if(n == 1 || (s == 1 && t == n) || (s == n && t == 1)) {
			printf("0\n");
			continue;
		}
		if(s == t) {
			printf("-1\n");
			continue;
		}
		if(s - t == 1 || s - t == -1) {
			printf("1\n");
			continue;
		}
		if(s == 1 || s == n) {
			printf("1\n");
			continue;
		}
		printf("2\n");
	}
	return 0;
}


C: 一棵完全二叉树的左右子树都为完全二叉树, 有一棵子树的最后一层是满的, 每一层的节点子树形态相同, 统计后递归求解另一颗子

树即可得到答案.

AC代码:

#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
#include "set"
using namespace std;
typedef long long ll;
ll n;
set<ll> s;
void dfs(ll x)
{
	if(x == 0 || s.count(x) > 0) return;
	s.insert(x);
	if((--x & 1) == 0) dfs(x >> 1);
	else {
		dfs(x >> 1);
		dfs((x >> 1) + 1);
	}
}
int main(int argc, char const *argv[])
{
	while(scanf("%lld", &n) != EOF) {
		s.clear();
		dfs(n);
		printf("%lu\n", s.size());
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值