Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <iterator>
- #include <unordered_map>
- #include <unordered_set>
- #include <string>
- class Graph {
- private:
- int size_g;
- std::vector<std::vector<int>> data;
- std::vector<int> used;
- public:
- std::vector<bool> isused;
- std::vector<int> colour;
- bool isisdouble = true;
- bool isiscycle = false;
- std::vector<int> cyclepath;
- std::unordered_map<int, int> parents;
- int max_path = 0;
- Graph() {
- }
- explicit Graph(int n) {
- data.resize(n);
- isused.resize(n);
- size_g = n;
- }
- void insert(int a, int b) {
- if (a != b) {
- data[a - 1].push_back(b);
- data[b - 1].push_back(a);
- }
- }
- void printgraph() {
- for (int i = 0; i < data.size(); i++) {
- for (auto j : data[i]) {
- std::cout << j << " ";
- }
- std::cout << '\n';
- }
- }
- std::vector<int> dfs(int a) {
- std::vector<int> result;
- if (!isused[a - 1]) {
- isused[a - 1] = true;
- result.push_back(a);
- for (int i = 0; i < data[a - 1].size(); i++) {
- if (!isused[data[a - 1][i] - 1]) {
- std::vector<int> preres;
- preres = dfs(data[a - 1][i]);
- result.insert(result.end(), preres.begin(), preres.end());
- }
- }
- }
- return result;
- }
- int sizetree(int a, int prev) {
- int max = -1;
- int second_max = -1;
- int b = 0;
- for (int i = 0; i < data[a - 1].size(); i++) {
- if (data[a - 1][i] != prev) {
- b = sizetree(data[a - 1][i], a) + 1;
- if (b >= max) {
- second_max = max;
- max = b;
- } else if (b < max && b > second_max) {
- second_max = b;
- }
- }
- }
- if (max + second_max + 2 > max_path) {
- max_path = max + second_max + 2;
- }
- return max;
- }
- };
- int main() {
- int N, M;
- int a, b;
- std::cin >> N;
- if (N != 0) {
- Graph graph(N);
- for (int i = 0; i < N - 1; i++) {
- std::cin >> a >> b;
- graph.insert(a, b);
- }
- graph.sizetree(1, -1);
- std::cout << graph.max_path;
- }
- }
Add Comment
Please, Sign In to add comment