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

再分析

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

相关推荐
博笙困了23 分钟前
AcWing学习——双指针算法
c++·算法
moonlifesudo1 小时前
322:零钱兑换(三种方法)
算法
NAGNIP19 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队20 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法
博笙困了1 天前
AcWing学习——差分
c++·算法
NAGNIP1 天前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP1 天前
大模型微调框架之LLaMA Factory
算法