查找三元组,以便在C ++中连接这些三元组的节点数最大
在本教程中,我们将讨论一个寻找三元组的程序,以使连接这些三元组的节点数量最大。
为此,我们将提供一个具有N个节点的树。我们的任务是找到一个三元组的节点,以使路径中覆盖的节点最大程度地将它们连接起来。
示例
#include <bits/stdc++.h> #define ll long long int #define MAX 100005 using namespace std; vector<int> nearNode[MAX]; bool isTraversed[MAX]; //存储所需的节点 int maxi = -1, N; int parent[MAX]; bool vis[MAX]; int startnode, endnode, midNode; //实现DFS搜索节点 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; } } } //查找直径的尾注 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)