在一定的约束条件下,将白色和黑色对象分配到最大组中
给定W个白色物体和B个黑色物体以及一个数字D,任务是找出是否有可能将白色和黑色物体分布到最大数量的组中,使得每个组至少包含每种类型的物体中的一种,并且每组不同类型物体的数量之差不超过D.
例子:
Input: W=2, B=5, D=2
Output:
YES
Explanation:
The distribution can be as follows: {W, B, B, B} and {W, B, B}.
Each group contains at least one W and at least one B, and the difference in each group does not exceed D.
Input: W=2, B=7, D=2
Output:
NO
方法:可能的最大组数为min(W, B)。让我们考虑, W ,那么最多可以有W个组,并且在每个组中只有一个W 。每组中B的最大数量为D+1 。因此, B的最大值应该小于W*(D+1)。这是唯一的必要条件。请按照以下步骤解决问题:
- 如果W大于B ,则交换W和B 。 (交换不会改变答案)
- 检查B是否大于W*(D+1) ,打印 NO。
- 否则,打印 YES。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if it is possible to distribute W and B
// into maximum groups possible
void isPossible(int W, int B, int D)
{
// If W is greater than B, swap them
if (W > B)
swap(W, B);
// Distribution is not possible
if (B > W * (D + 1))
cout << "NO" << endl;
// Distribution is possible
else
cout << "YES" << endl;
}
// Driver code
int main()
{
// Input
int W = 2;
int B = 5;
int D = 2;
// Function call
isPossible(W, B, D);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG
{
// Function to check if it is possible to distribute W
// and B
// into maximum groups possible
public static void isPossible(int W, int B, int D)
{
// If W is greater than B, swap them
if (W > B) {
int temp = W;
W = B;
B = temp;
}
// Distribution is not possible
if (B > W * (D + 1))
System.out.println("NO");
// Distribution is possible
else
System.out.println("YES");
}
// Driver code
public static void main(String[] args)
{
// Input
int W = 2;
int B = 5;
int D = 2;
// Function call
isPossible(W, B, D);
}
}
// This code is contributed by Potta Lokesh
Python3
# Python 3 program for the above approach
# Function to check if it is possible to distribute W and B
# into maximum groups possible
def isPossible(W, B, D):
# If W is greater than B, swap them
if (W > B):
temp = W
W = B
B = temp
# Distribution is not possible
if (B > W * (D + 1)):
print("NO")
# Distribution is possible
else:
print("YES")
# Driver code
if __name__ == '__main__':
# Input
W = 2
B = 5
D = 2
# Function call
isPossible(W, B, D)
# This code is contributed by bgangwar59.
C#
// C# program for the above approach
using System;
class GFG {
// Function to check if it is possible to distribute W
// and B
// into maximum groups possible
static void isPossible(int W, int B, int D)
{
// If W is greater than B, swap them
if (W > B) {
int temp = W;
W = B;
B = temp;
}
// Distribution is not possible
if (B > W * (D + 1))
Console.WriteLine("NO");
// Distribution is possible
else
Console.WriteLine("YES");
}
// Driver code
public static void Main()
{
// Input
int W = 2;
int B = 5;
int D = 2;
// Function call
isPossible(W, B, D);
}
}
// This code is contributed by rishavmahato348.
Javascript
输出
YES
时间复杂度: O(1)
辅助空间: O(1)