【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;
}

再分析

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

相关推荐
JieE21221 小时前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack201 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树1 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2122 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2122 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术2 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦2 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050732 天前
(一)小红的数组操作
算法·编程语言
怕浪猫2 天前
Electron 系列文章封面图
算法·架构·前端框架