给定图的最小生成树成本
给定一个名为 V 1 , V 2 , V 3 , ..., V n的V节点 (V > 2) 的无向图。两个节点V i和V j相互连接当且仅当0 < |我 - j | ≤ 2 。任何顶点对(V i , V j )之间的每条边都被分配了一个权重i + j 。任务是找到具有V个节点的此类图的最小生成树的成本。
例子:
Input: V = 4
Output: 13
Input: V = 5
Output: 21
方法:从具有最小节点(即3个节点)的图开始,最小生成树的成本将为7。现在对于可以添加到该图中的从第四个节点开始的每个节点i ,第i个节点只能是连接到第 (i – 1 )和( i – 2)节点,最小生成树将仅包含具有最小权重的节点,因此新添加的边将具有权重i + (i – 2) 。
So addition of fourth node will increase the overall weight as 7 + (4 + 2) = 13
Similarly adding fifth node, weight = 13 + (5 + 3) = 21
…
For nth node, weight = weight + (n + (n – 2)).
这可以概括为权重 = V 2 – V + 1 ,其中V是图中的节点总数。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function that returns the minimum cost
// of the spanning tree for the required graph
int getMinCost(int Vertices)
{
int cost = 0;
// Calculating cost of MST
cost = (Vertices * Vertices) - Vertices + 1;
return cost;
}
// Driver code
int main()
{
int V = 5;
cout << getMinCost(V);
return 0;
}
Java
// Java implementation of the approach
class GfG
{
// Function that returns the minimum cost
// of the spanning tree for the required graph
static int getMinCost(int Vertices)
{
int cost = 0;
// Calculating cost of MST
cost = (Vertices * Vertices) - Vertices + 1;
return cost;
}
// Driver code
public static void main(String[] args)
{
int V = 5;
System.out.println(getMinCost(V));
}
}
// This code is contributed by
// Prerna Saini.
C#
// C# implementation of the above approach
using System;
class GfG
{
// Function that returns the minimum cost
// of the spanning tree for the required graph
static int getMinCost(int Vertices)
{
int cost = 0;
// Calculating cost of MST
cost = (Vertices * Vertices) - Vertices + 1;
return cost;
}
// Driver code
public static void Main()
{
int V = 5;
Console.WriteLine(getMinCost(V));
}
}
// This code is contributed by Ryuga
Python3
# python3 implementation of the approach
# Function that returns the minimum cost
# of the spanning tree for the required graph
def getMinCost( Vertices):
cost = 0
# Calculating cost of MST
cost = (Vertices * Vertices) - Vertices + 1
return cost
# Driver code
if __name__ == "__main__":
V = 5
print (getMinCost(V))
PHP
Javascript
输出:
21