当前位置:网站首页>【Leetcode】2360. Longest Cycle in a Graph
【Leetcode】2360. Longest Cycle in a Graph
2022-08-01 23:47:00 【记录算法题解】
题目地址:
https://leetcode.com/problems/longest-cycle-in-a-graph/
给定一个 n n n个点的有向图,每个点最多只有一条出边。给定每个点的出边指向的点,如果不存在则以 − 1 -1 −1标记。求长度最大的环的长度。若不存在环,则返回 − 1 -1 −1。
当然可以直接用Tarjan求一下最大的强联通分量。由于每个点只有一条出边,所以每个点只会存在于一个环中,从而可以直接模拟,直接从每个点出发,并且做标记,同时用一个哈希表记录步数。代码如下:
class Solution {
public:
int longestCycle(vector<int>& e) {
int n = e.size();
vector<bool> vis(n);
int res = -1;
for (int i = 0; i < n; i++) {
if (!vis[i]) {
unordered_map<int, int> mp;
int x = i, time_stamp = 0;
while (true) {
mp[x] = ++time_stamp;
vis[x] = true;
// 找到环了
if (mp.count(e[x])) {
res = max(res, mp[x] - mp[e[x]] + 1);
break;
}
// 走到了死胡同
if (e[x] == -1 || vis[e[x]]) break;
// 向后走一步
x = e[x];
}
}
}
return res;
}
};
时空复杂度 O ( n ) O(n) O(n)。
边栏推荐
猜你喜欢
随机推荐
Always use "noopener" or "noreferrer" for links that open in a new tab
【MySQL篇】初识数据库
Oracle database is set to read-only and read-write
Deep Learning Fundamentals - Numpy-based Recurrent Neural Network (RNN) implementation and backpropagation training
Flink学习第五天——Flink可视化控制台依赖配置和界面介绍
When using DocumentFragments add a large number of elements
2022 6th Strong Net Cup Part WP
yay 报错 response decoding failed: invalid character ‘<‘ looking for beginning of value;
Flink Yarn Per Job - 提交流程一
Flink Yarn Per Job - CliFrontend
Get piggy homestay (short-term rental) data
Chapter 11 Working with Dates and Times
qt-faststart installation and use
@Resource和@Autowired的区别
IDEA common plugins
正则表达式
C language - branch statement and loop statement
FAST-LIO2代码解析(二)
ansible模块--copy模块
Special characters & escapes in bat






![[C language advanced] file operation (2)](/img/4d/49d9603aeed16f1600d69179477eb3.png)


