最大化不属于图中任何边的节点数
给定一个具有 n 个节点和 m 个边的图。找到不属于任何边的最大可能节点数(m 将始终小于或等于完整图中的边数)。
例子:
Input: n = 3, m = 3
Output: Maximum Nodes Left Out: 0
Since it is a complete graph.
Input: n = 7, m = 6
Output: Maximum Nodes Left Out: 3
We can construct a complete graph on 4 vertices using 6 edges.
方法:遍历所有 n 并查看如果我们制作一个完整的图,我们在哪些节点上获得的边数超过 m 说它是 K。答案是nk 。
- 可用于在 n 个节点上形成图的最大边数为n * (n – 1) / 2 (完整图)。
- 然后找到最大 n 的个数,它将使用 m 或小于 m 的边来形成一个完整的图。
- 如果仍然有边,那么它将只覆盖一个以上的节点,就好像它会覆盖一个以上的节点一样,这不是 n 的最大值。
以下是上述方法的实现:
C++
// C++ program to illustrate above approach
#include
#define ll long long int
using namespace std;
// Function to return number of nodes left out
int answer(int n, int m)
{
int i;
for (i = 0; i <= n; i++) {
// Condition to terminate, when
// m edges are covered
if ((i * (i - 1)) >= 2 * m)
break;
}
return n - i;
}
// Driver Code
int main()
{
int n = 7;
int m = 6;
cout << answer(n, m) << endl;
}
Java
// Java program to illustrate above approach
import java.io.*;
class GFG {
// Function to return number of nodes left out
static int answer(int n, int m)
{
int i;
for (i = 0; i <= n; i++) {
// Condition to terminate, when
// m edges are covered
if ((i * (i - 1)) >= 2 * m)
break;
}
return n - i;
}
// Driver Code
public static void main (String[] args) {
int n = 7;
int m = 6;
System.out.print( answer(n, m));
}
}
// This code is contributed by anuj_67..
Python3
# Python 3 program to illustrate
# above approach
# Function to return number of
# nodes left out
def answer(n, m):
for i in range(0, n + 1, 1):
# Condition to terminate, when
# m edges are covered
if ((i * (i - 1)) >= 2 * m):
break
return n - i
# Driver Code
if __name__ == '__main__':
n = 7
m = 6
print(answer(n, m))
# This code is contributed
# by Surendra_Gangwar
C#
// C# program to illustrate
// above approach
using System;
class GFG
{
// Function to return number
// of nodes left out
static int answer(int n, int m)
{
int i;
for (i = 0; i <= n; i++)
{
// Condition to terminate, when
// m edges are covered
if ((i * (i - 1)) >= 2 * m)
break;
}
return n - i;
}
// Driver Code
static public void Main ()
{
int n = 7;
int m = 6;
Console.WriteLine(answer(n, m));
}
}
// This code is contributed
// by anuj_67
PHP
= 2 * $m)
break;
}
return $n - $i;
}
// Driver Code
$n = 7;
$m = 6;
echo answer($n, $m) + "\n";
// This code is contributed
// by Akanksha Rai(Abby_akku)
?>
Javascript
输出:
3