Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <vector>
- #include <stack>
- #include <set>
- #include <stdlib.h>
- #include <algorithm>
- #include <functional>
- using namespace std;
- stack<int> q;
- int t = 0;
- void dfs(vector<string>& names, vector<vector<bool>>& relations, int node, vector<bool>& visited, vector<int>& low,
- vector<int>& pre, vector<bool>& stack, vector<vector<string>>& result)
- {
- visited[node] = stack[node] = true;
- low[node] = pre[node] = t;
- q.push(node);
- ++t;
- for (int i = 0; i < relations[node].size(); ++i)
- {
- if (!visited[i] && relations[i][node])
- {
- dfs(names, relations, i, visited, low, pre, stack, result);
- low[node] = min(low[i], low[node]);
- }
- else if (stack[i])
- low[node] = min(low[node], pre[i]);
- }
- if (low[node] == pre[node])
- {
- int x;
- vector<string> comp;
- do
- {
- x = q.top();
- q.pop();
- comp.push_back(names[x]);
- stack[x] = false;
- low[x] = INT_MAX;
- } while(x != node);
- if (comp.size() > 1)
- sort(comp.begin(), comp.end());
- result.push_back(comp);
- }
- }
- bool comp(vector<string>& first, vector<string>& second)
- {
- return first[0] < second[0];
- }
- vector<vector<string>> getList(vector<string>& names, vector<vector<bool>>& relations)
- {
- vector<vector<string>> result;
- vector<bool> visited(names.size(), false);
- vector<int> low(names.size(), 0);
- vector<int> pre(names.size(), 0);
- vector<bool> stack(names.size(), false);
- for (int i = 0; i < relations.size(); ++i)
- if (!visited[i])
- dfs(names, relations, i, visited, low, pre, stack, result);
- sort(result.begin(), result.end(), comp);
- t = 0;
- return result;
- }
- int main()
- {
- vector<string> names = vector<string>();
- vector<vector<bool>> relations;
- int startIndex;
- ifstream fin;
- fin.open("../input.txt");
- if (fin.is_open())
- {
- string str = "";
- getline(fin, str);
- while (str != "#")
- {
- names.emplace_back(str.substr(str.find(' ') + 1));
- getline(fin, str);
- }
- relations = vector<vector<bool>>(names.size());
- for (int i = 0; i < names.size(); i++)
- {
- relations[i] = vector<bool>(names.size());
- for (int j = 0; j < names.size(); j++)
- relations[i][j] = false;
- }
- getline(fin, str);
- while (fin)
- {
- int a = stoi(str.substr(0, str.find(' '))) - 1;
- int b = stoi(str.substr(str.find(' '))) - 1;
- relations[a][b] = true;
- getline(fin, str);
- }
- fin.close();
- }
- vector<vector<string>> res = getList(names, relations);
- fstream fout;
- fout.open("../output.txt", ios::out);
- for (int i = 0; i < res.size(); i++)
- {
- for (int j = 0; j < res[i].size(); j++)
- fout << res[i][j] << "\n";
- if (i != res.size() - 1)
- fout << "\n";
- }
- fout.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement