当前位置:   article > 正文

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

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

题目

问题代码

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. const int N = 1e6+10;
  4. int n;
  5. int porter[N];
  6. int ans;
  7. int sign[N];
  8. bool used;
  9. void dfs(int now, int cnt)
  10. {
  11. if(sign[now] && used)
  12. {
  13. ans = max(ans, cnt);
  14. return;
  15. }
  16. if(!sign[now])
  17. {
  18. cnt++, sign[now] = 1;
  19. dfs(porter[now], cnt);
  20. }
  21. if(!used)
  22. {
  23. used = true;
  24. dfs(now-1, cnt);
  25. dfs(now+1, cnt);
  26. used = false;
  27. }
  28. }
  29. int main()
  30. {
  31. ios::sync_with_stdio(0);
  32. cin.tie(0);
  33. cout.tie(0);
  34. cin >> n;
  35. for(int i = 1; i <= n ; i++) cin >> porter[i];
  36. for(int i = 1; i <= n; i++) dfs(i, 0);
  37. cout << ans;
  38. return 0;
  39. }

分析

修改

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

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. const int N = 1e6+10;
  4. int n;
  5. int porter[N];
  6. int ans;
  7. int sign[N];
  8. bool used;
  9. void dfs(int now, int cnt)
  10. {
  11. if(sign[now] && used)
  12. {
  13. ans = max(ans, cnt);
  14. return;
  15. }
  16. if(!sign[now])
  17. {
  18. cnt++, sign[now] = 1;
  19. dfs(porter[now], cnt);
  20. sign[now] = 0;
  21. }
  22. if(!used)
  23. {
  24. sign[now] = 1;
  25. used = true;
  26. if(now-1 >= 1) dfs(now-1, cnt);
  27. //used = false;
  28. //sign[now] = 0;
  29. sign[now] = 1;
  30. used = true;
  31. if(now+1 <= n) dfs(now+1, cnt);
  32. used = false;
  33. sign[now] = 0;
  34. }
  35. }
  36. int main()
  37. {
  38. ios::sync_with_stdio(0);
  39. cin.tie(0);
  40. cout.tie(0);
  41. cin >> n;
  42. for(int i = 1; i <= n ; i++) cin >> porter[i];
  43. for(int i = 1; i <= n; i++) dfs(i, 0);
  44. cout << ans;
  45. return 0;
  46. }

再分析

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/923881
推荐阅读
相关标签
  

闽ICP备14008679号