用 C++ 算法找到三个结点的连接数最多的元组
本教程将讨论一个用来找到三个结点的连接数最多的元组的程序。
为此,我们将获得一棵包含 N 个结点的树。我们的任务是找到这样三个结点,使连接它们的路劲中覆盖的结点数最多。
示例
#include <bits/stdc++.h> #define ll long long int #define MAX 100005 using namespace std; vector<int> nearNode[MAX]; bool isTraversed[MAX]; //storing the required nodes int maxi = -1, N; int parent[MAX]; bool vis[MAX]; int startnode, endnode, midNode; //implementing DFS to search nodes void performDFS(int u, int count) { isTraversed[u] = true; int temp = 0; for (int i = 0; i < nearNode[u].size(); i++) { if (!isTraversed[nearNode[u][i]]) { temp++; performDFS(nearNode[u][i], count + 1); } } if (temp == 0) { if (maxi < count) { maxi = count; startnode = u; } } } void performDFS2(int u, int count) { isTraversed[u] = true; int temp = 0; for (int i = 0; i < nearNode[u].size(); i++) { if (!isTraversed[nearNode[u][i]] && !vis[nearNode[u][i]]) { temp++; performDFS2(nearNode[u][i], count + 1); } } if (temp == 0) { if (maxi < count) { maxi = count; midNode = u; } } } //finding endnote of diameter void performDFS1(int u, int count) { isTraversed[u] = true; int temp = 0; for (int i = 0; i < nearNode[u].size(); i++) { if (!isTraversed[nearNode[u][i]]) { temp++; parent[nearNode[u][i]] = u; performDFS1(nearNode[u][i], count + 1); } } if (temp == 0) { if (maxi < count) { maxi = count; endnode = u; } } } void calcTreeVertices() { performDFS(1, 0); for (int i = 0; i <= N; i++) isTraversed[i] = false; maxi = -1; performDFS1(startnode, 0); for (int i = 0; i <= N; i++) isTraversed[i] = false; int x = endnode; vis[startnode] = true; while (x != startnode) { vis[x] = true; x = parent[x]; } maxi = -1; for (int i = 1; i <= N; i++) { if (vis[i]) performDFS2(i, 0); } } int main() { N = 4; nearNode[1].push_back(6); nearNode[2].push_back(0); nearNode[1].push_back(7); nearNode[3].push_back(0); nearNode[1].push_back(2); nearNode[4].push_back(0); calcTreeVertices(); cout << "Nodes: (" << startnode << ", " << endnode << ", " << midNode << ")"; return 0; }
输出
Nodes: (0, 0, 0)
广告