牛客664989630号 level
获赞
0
粉丝
0
关注
1
看过 TA
2
清华大学
2024
市场
IP属地:湖北
暂未填写个人简介
私信
关注
2024-10-14 19:22
清华大学 市场
循环依赖 #include <iostream>#include <vector>#include <stack>#include <algorithm>using namespace std;const int MAX = 10000;vector<int> graph[MAX];int visited[MAX] = {0};int inStack[MAX] = {0};stack<int> stk;vector<int> result;bool dfs(int u) {if (visited[u] == 1) {if (!stk.empty() && inStack[u] == 1) {while (!stk.empty() && stk.top() != u) {result.push_back(stk.top());stk.pop();}result.push_back(u);stk.pop();return true;} else {return false;}}visited[u] = 1;stk.push(u);inStack[u] = 1;for (int v : graph[u]) {if (dfs(v)) {return true;}}inStack[u] = 0;stk.pop();return false;}int main() {int n;cin >> n;for (int i = 0; i < MAX; i++) {graph[i].clear();}for (int i = 0; i < n; i++) {int k;cin >> k;int a;cin >> a;for (int j = 0; j < k - 1; j++) {int b;cin >> b;graph[a].push_back(b);}}for (int i = 1; i < MAX; i++) {if (visited[i] == 0) {if (dfs(i)) {break;}}}if (!result.empty()) {reverse(result.begin(), result.end());int minValue = *min_element(result.begin(), result.end());int index = find(result.begin(), result.end(), minValue) - result.begin();vector<int> finalResult(result.begin() + index, result.end());finalResult.insert(finalResult.end(), result.begin(), result.begin() + index + 1);for (int node : finalResult) {cout << node << " ";}}return 0;}// vx公众号关注TechGuide,专业生产offer收割机,代码可能需要少量调试。
0 点赞 评论 收藏
分享

创作者周榜

更多
关注他的用户也关注了:
牛客网
牛客网在线编程
牛客网题解
牛客企业服务