博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
洛谷 2921 记忆化搜索 tarjan 基环外向树
阅读量:4308 次
发布时间:2019-06-06

本文共 1811 字,大约阅读时间需要 6 分钟。

洛谷 2921 记忆化搜索 tarjan


()


做这题的经历有点玄学,,起因是某个random题的同学突然发现了一个0提交0通过的题目,然后就引发了整个机房的兴趣,,然后,,就变成了16提交7通过,,

初看上去这题目就是记忆化搜索,但是环的存在使得普通的记忆化会导致漏解,继续观察发现整张图为n个点n条边,即是多个基环外向树,使用tarjan找到图中的环,显然可知,对于环上一点,能取到的最大值是环的长度,对于环外一点,能取到的最大值是它走到环的长度加上环长,之后采用记忆化搜索或dp即可得解

Warning:

  1. 从样例可以显然发现,存在自环
  2. 开始写tarjan时错误的理解了low数组的含义,将其与from数组混淆

int

#include 
#include
#include
const int maxn = 100000 + 100;int next[maxn];int dfn[maxn], low[maxn], size[maxn], sta[maxn];int from[maxn];int vis[maxn];int stackTop = 0;int tim = 0;int n;int ans[maxn];void tarjan(int x) { tim++; stackTop++; sta[stackTop] = x; dfn[x] = low[x] = tim; vis[x] = 1; if (!dfn[next[x]]) { tarjan(next[x]); low[x] = std :: min(low[next[x]], low[x]); } else if (vis[next[x]]) { low[x] = std :: min(low[x], dfn[next[x]]); } if (low[x] == dfn[x]) { while (sta[stackTop] != x) { size[x]++; from[sta[stackTop]] = x; vis[sta[stackTop]] = 0; stackTop--; } vis[x] = 0; stackTop--; size[x]++; from[x] = x; }}void dfs(int x) { if (ans[x] > 0) return; if (from[x] != x || size[x] > 1) { ans[x] = size[from[x]]; return; } else if (next[x] == x) { ans[x] = 1; return; } else { dfs(next[x]); ans[x] = 1 + ans[next[x]]; }}int main () { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &next[i]); } for (int i = 1; i <= n; i++) { if (!dfn[i]) tarjan(i); } //for (int i = 1; i <= n; i++) // printf("%d\n", from[i]); for (int i = 1; i <= n; i++) if (ans[i] == 0) dfs(i); for (int i = 1; i <= n; i++) printf("%d\n", ans[i]); return 0;}

转载于:https://www.cnblogs.com/CtsNevermore/p/6018135.html

你可能感兴趣的文章
mongodb查询优化
查看>>
五步git操作搞定Github中fork的项目与原作者同步
查看>>
git 删除远程分支
查看>>
删远端分支报错remote refs do not exist或git: refusing to delete the current branch解决方法
查看>>
python multiprocessing遇到Can’t pickle instancemethod问题
查看>>
APP真机测试及发布
查看>>
通知机制 (Notifications)
查看>>
10 Things You Need To Know About Cocoa Auto Layout
查看>>
一个异步网络请求的坑:关于NSURLConnection和NSRunLoopCommonModes
查看>>
iOS 如何放大按钮点击热区
查看>>
ios设备唯一标识获取策略
查看>>
获取推送通知的DeviceToken
查看>>
Could not find a storyboard named 'Main' in bundle NSBundle
查看>>
CocoaPods安装和使用教程
查看>>
Beginning Auto Layout Tutorial
查看>>
block使用小结、在arc中使用block、如何防止循环引用
查看>>
iPhone开发学习笔记002——Xib设计UITableViewCell然后动态加载
查看>>
iOS开发中遇到的问题整理 (一)
查看>>
Swift code into Object-C 出现 ***-swift have not found this file 的问题
查看>>
为什么你的App介绍写得像一坨翔?
查看>>