给定两个整数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)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live