给定两个整数N和E ,该整数表示无向图的节点数和边数,任务是在不使用任何自环的情况下,使未连接到图中任何其他节点的节点数最大化。
例子:
Input: N = 5, E = 1
Output: 3
Explanation:
Since there is only 1 edge in the graph which can be used to connect two nodes.
Therefore, three node remains disconnected.
Input: N = 5, E = 2
Output: 2
方法:该方法基于以下想法:为了最大化断开连接的节点数,直到每两个不同的节点都被连接后,新节点才会添加到图中。以下是解决此问题的步骤:
- 初始化两个变量curr和rem来分别存储连接的节点和未分配的边。
- 如果rem变为0,则所需答案将为N – curr 。
- 否则,将curr的值增加1。
- 因此,当前步骤中保持两个不同节点保持连接所需的最大边为min(rem,curr) 。从rem减去它并增加curr 。
- 重复此过程,直到rem降为零。
- 最后,打印N-curr 。
下面是上述方法的实现:
C++
// C++ implementation of
// the above approach
#include
using namespace std;
// Function which returns
// the maximum number of
// isolated nodes
int maxDisconnected(int N, int E)
{
// Used nodes
int curr = 1;
// Remaining edges
int rem = E;
// Count nodes used
while (rem > 0) {
rem = rem
- min(
curr, rem);
curr++;
}
// If given edges are non-zero
if (curr > 1) {
return N - curr;
}
else {
return N;
}
}
// Driver Code
int main()
{
// Given N and E
int N = 5, E = 1;
// Function Call
cout << maxDisconnected(N, E);
return 0;
}
Java
// Java implementation of
// the above approach
import java.util.*;
class GFG{
// Function which returns
// the maximum number of
// isolated nodes
static int maxDisconnected(int N, int E)
{
// Used nodes
int curr = 1;
// Remaining edges
int rem = E;
// Count nodes used
while (rem > 0)
{
rem = rem - Math.min(
curr, rem);
curr++;
}
// If given edges are non-zero
if (curr > 1)
{
return N - curr;
}
else
{
return N;
}
}
// Driver Code
public static void main(String[] args)
{
// Given N and E
int N = 5, E = 1;
// Function call
System.out.print(maxDisconnected(N, E));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of
# the above approach
# Function which returns
# the maximum number of
# isolated nodes
def maxDisconnected(N, E):
# Used nodes
curr = 1
# Remaining edges
rem = E
# Count nodes used
while (rem > 0):
rem = rem - min(curr, rem)
curr += 1
# If given edges are non-zero
if (curr > 1):
return N - curr
else:
return N
# Driver Code
if __name__ == '__main__':
# Given N and E
N = 5
E = 1
# Function call
print(maxDisconnected(N, E))
# This code is contributed by mohit kumar 29
C#
// C# implementation of
// the above approach
using System;
class GFG{
// Function which returns
// the maximum number of
// isolated nodes
static int maxDisconnected(int N,
int E)
{
// Used nodes
int curr = 1;
// Remaining edges
int rem = E;
// Count nodes used
while (rem > 0)
{
rem = rem - Math.Min(curr, rem);
curr++;
}
// If given edges are non-zero
if (curr > 1)
{
return N - curr;
}
else
{
return N;
}
}
// Driver Code
public static void Main(String[] args)
{
// Given N and E
int N = 5, E = 1;
// Function call
Console.Write(maxDisconnected(N, E));
}
}
// This code is contributed by 29AjayKumar
输出:
3
时间复杂度: O(E)
辅助空间: O(1)