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

再分析

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

相关推荐
jiao000011 小时前
数据结构——队列
c语言·数据结构·算法
迷迭所归处2 小时前
C++ —— 关于vector
开发语言·c++·算法
leon6252 小时前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab
CV工程师小林2 小时前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
Navigator_Z3 小时前
数据结构C //线性表(链表)ADT结构及相关函数
c语言·数据结构·算法·链表
Aic山鱼3 小时前
【如何高效学习数据结构:构建编程的坚实基石】
数据结构·学习·算法
天玑y3 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
sjsjs113 小时前
【数据结构-一维差分】力扣1893. 检查是否区域内所有整数都被覆盖
数据结构·算法·leetcode
redcocal4 小时前
地平线秋招
python·嵌入式硬件·算法·fpga开发·求职招聘
码了三年又三年4 小时前
【算法】滑动窗口—找所有字母异位词
算法