【2024蓝桥杯/C++/B组/传送阵】

题目

问题代码

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

const int N = 1e6+10;
int n;
int porter[N];
int ans;
int sign[N];
bool used;

void dfs(int now, int cnt)
{
    if(sign[now] && used)
    {
        ans = max(ans, cnt);
        return;
    }

    if(!sign[now])
    {
        cnt++, sign[now] = 1; 
        dfs(porter[now], cnt);
    }

    if(!used)
    {
        used = true;
        dfs(now-1, cnt);
        dfs(now+1, cnt);
        used = false;
    }
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    
    cin >> n;
    for(int i = 1; i <= n ; i++) cin >> porter[i];

    for(int i = 1; i <= n; i++) dfs(i, 0);

    cout << ans;

    return 0;
}

分析

修改

我想了一下,可能是由于回溯的问题。因为我定的是全局变量sign和used,所以回溯应该要逐个回溯。而且我还忘了边界限制。修改如下

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

const int N = 1e6+10;
int n;
int porter[N];
int ans;
int sign[N];
bool used;

void dfs(int now, int cnt)
{
    if(sign[now] && used)
    {
        ans = max(ans, cnt);
        return;
    }

    if(!sign[now])
    {
        cnt++, sign[now] = 1; 
        dfs(porter[now], cnt);
        sign[now] = 0;
    }

    if(!used)
    {
        sign[now] = 1;
        used = true;
        if(now-1 >= 1) dfs(now-1, cnt);
        //used = false;
        //sign[now] = 0;
        sign[now] = 1;
        used = true;
        if(now+1 <= n) dfs(now+1, cnt);
        used = false;
        sign[now] = 0;
    }
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    
    cin >> n;
    for(int i = 1; i <= n ; i++) cin >> porter[i];

    for(int i = 1; i <= n; i++) dfs(i, 0);

    cout << ans;

    return 0;
}

再分析

可以看出原本不过的样例过了。说明修改可能正确了,但是因此也增加了时间消耗。

相关推荐
yi01144 分钟前
DAY28: LeetCode 111. 二叉树的最小深度
人工智能·笔记·python·算法·leetcode·二叉树·递归
wuyk5551 小时前
27.LeetCode 2265. 统计值等于子树平均值的节点数 —— 后序遍历实战
stm32·单片机·嵌入式硬件·算法
xiangyun611 小时前
C++ list 模拟实现(二):const迭代器与反向迭代器,模板的黑魔法
开发语言·数据库·c++·算法·stl·list
xxwl5851 小时前
三、区域赛算法模版第三章---字符串相关算法
笔记·学习·算法
信奥卷王1 小时前
[GESP202509 六级] 划分字符串(含视频)
数据结构·算法
酒醉的胡铁2 小时前
相似度搜索的常见算法
算法·ai
局部有解2 小时前
Leetcode Hot100 - 最长连续序列
算法·leetcode·职场和发展
行者全栈架构师2 小时前
给开源 Rust 工具加一个新检查项,TRAE 帮我从想法跑到构建产物:全链路实战
前端·算法·架构
行者全栈架构师2 小时前
【鸿蒙心迹】冷启动从 2.8s 优化到 0.9s——耗时拆解与数据对比实战(HarmonyOS 7.x)
前端·算法·架构
LXY_BUAA3 小时前
《嵌入式操作系统》_framebuffer驱动_20261008
linux·运维·算法