给定一个数字N ,它是图中节点的数量,任务是找到 N 顶点图可以具有的最大边数,使得图没有三角形(这意味着不应该有任何三个边 A,图中的 B、C 使得 A 连接到 B,B 连接到 C,C 连接到 A)。图不能包含自环或多边。
例子:
Input: N = 4
Output: 4
Explanation:
Input: N = 3
Output: 2
Explanation:
If there are three edges in 3-vertex graph then it will have a triangle.
方法:这个问题可以使用曼特尔定理来解决,该定理指出图中不包含任何三角形的最大边数是 floor(n 2 /4)。换句话说,必须删除近一半的边才能获得无三角形图。
曼特尔定理如何运作?
对于任何图,使得该图是无三角形的,那么对于任何顶点 Z 只能连接到来自 x 和 y 的任何一个顶点,即对于连接在 x 和 y 之间的任何边,d(x) + d(y) ≤ N,其中 d(x) 和 d(y) 是顶点 x 和 y 的度数。
- 那么,所有顶点的度数——
- 通过柯西-施瓦茨不等式——
- 因此,4m 2 / n ≤ mn,这意味着m ≤ n 2 / 4
下面是上述方法的实现:
C++
// C++ implementation to find the maximum
// number of edges for triangle free graph
#include
using namespace std;
// Function to find the maximum number of
// edges in a N-vertex graph.
int solve(int n)
{
// According to the Mantel's theorem
// the maximum number of edges will be
// floor of [(n^2)/4]
int ans = (n * n / 4);
return ans;
}
// Driver Function
int main()
{
int n = 10;
cout << solve(n) << endl;
return 0;
}
Java
// Java implementation to find the maximum
// number of edges for triangle free graph
class GFG
{
// Function to find the maximum number of
// edges in a N-vertex graph.
public static int solve(int n)
{
// According to the Mantel's theorem
// the maximum number of edges will be
// floor of [(n^2)/4]
int ans = (n * n / 4);
return ans;
}
// Driver code
public static void main(String args[])
{
int n = 10;
System.out.println(solve(n));
}
}
// This code is contributed by divyamohan123
C#
// C# implementation to find the maximum
// number of edges for triangle free graph
using System;
class GFG
{
// Function to find the maximum number of
// edges in a N-vertex graph.
public static int solve(int n)
{
// According to the Mantel's theorem
// the maximum number of edges will be
// floor of [(n^2)/4]
int ans = (n * n / 4);
return ans;
}
// Driver code
public static void Main()
{
int n = 10;
Console.WriteLine(solve(n));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation to find the maximum
# number of edges for triangle free graph
# Function to find the maximum number of
# edges in a N-vertex graph.
def solve(n):
# According to the Mantel's theorem
# the maximum number of edges will be
# floor of [(n^2)/4]
ans = (n * n // 4)
return ans
# Driver Function
if __name__ == '__main__':
n = 10
print(solve(n))
# This code is contributed by mohit kumar 29
Javascript
输出:
25
时间复杂度: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live