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 <algorithm>
- #include <list>
- using namespace std;
- vector<string> names;
- vector<vector<string>> result;
- bool compare_groups(const vector<string> &a, const vector<string> &b) {
- return a.front() < b.front();
- }
- void strong_connect(int curr, vector<vector<bool>> &relations, int *pre, int *low, bool *inStack, stack<int> &st,
- int &index) {
- pre[curr] = index;
- low[curr] = index;
- index++;
- st.push(curr);
- inStack[curr] = true;
- for (int child = 0; child < relations.size(); ++child) {
- if (!relations[curr][child])
- continue;
- if (pre[child] == -1) {
- strong_connect(child, relations, pre, low, inStack, st, index);
- low[curr] = min(low[curr], low[child]);
- } else {
- if (inStack[child]) {
- low[curr] = min(low[curr], pre[child]);
- }
- }
- }
- if (low[curr] == pre[curr]) {
- vector<string> group;
- int node;
- do {
- node = st.top();
- inStack[node] = false;
- st.pop();
- group.push_back(names[node]);
- } while (node != curr);
- sort(group.begin(), group.end());
- result.push_back(group);
- }
- }
- // алгоритм тарьяна
- void getList(vector<vector<bool>> &relations) {
- int *pre = new int[relations.size()];
- int *low = new int[relations.size()];
- bool *inStack = new bool[relations.size()];
- for (int i = 0; i < relations.size(); ++i) {
- // -1 значит непосещённая
- pre[i] = -1;
- low[i] = -1;
- inStack[i] = false;
- }
- int index = 0;
- stack<int> st;
- for (int i = 0; i < relations.size(); ++i) {
- if (pre[i] == -1) {
- strong_connect(i, relations, pre, low, inStack, st, index);
- }
- }
- sort(result.begin(), result.end(), compare_groups);
- delete[] pre;
- delete[] low;
- delete[] inStack;
- }
- 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();
- }
- result = vector<vector<string>>();
- getList(relations);
- fstream fout;
- fout.open("output.txt", ios::out);
- for (int i = 0; i < result.size(); i++) {
- for (int j = 0; j < result[i].size(); j++)
- fout << result[i][j] << "\n";
- fout << "\n";
- }
- fout.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement