给定数字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.
方法:此问题可使用曼特尔定理其中指出,在图中的边,而不含有任何三角形的最大数目是地板来解决(N 2/4)。换句话说,必须删除几乎一半的边缘才能获得无三角形的图形。
曼特尔定理是如何工作的?
对于任何图,如果该图是无三角形的,则对于任何顶点Z只能连接到x和y中任一顶点,即对于连接在x和y之间的任何边,d(x)+ d(y)≤ N,其中d(x)和d(y)是顶点x和y的度数。
- 然后,所有顶点的度–
- 由柯西·舒瓦兹(Cauchy-Schwarz)不等式–
- 因此,4M 2 / N≤MN,这意味着米≤Ñ四分之二
下面是上述方法的实现:
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
输出:
25
时间复杂度: O(1)