给定四个整数l , m , x和y 。任务是检查是否可以创建由l 0 , m 1 , x“ 01”和y“ 10”作为子序列的二进制字符串。
例子:
Input: l = 3, m = 2, x = 4, y = 2
Output: Yes
Possible string is “00110”. It contains 3 0’s, 2 1’s,
4 “01” sub-sequences and 2 “10” sub-sequences.
Input: l = 3, m = 2, x = 4, y = 3
Output: No
No such binary string exists.
方法:可能的字符串始终为00…11…00…的形式。首先由一些零组成,然后由所有零组成,然后由剩余的零组成。
假设l1为1之前的零个数, l2为1后面的零个数,则等式为:
- l1 + l2 = l (零总数)。
- l1 * m = x (“ 01”子序列数)。
- m * l2 = y (“ 10”个子序列的数量)。
从以上三个方程式中,我们得到x + y = l * m 。如果对于给定的值,此方程式失败,则该字符串不可能,否则打印Yes 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function that returns true if it is possible to
// make a binary string consisting of l 0's, m 1's,
// x "01" sub-sequences and y "10" sub-sequences
bool isPossible(int l, int m, int x, int y)
{
if (l * m == x + y)
return true;
return false;
}
// Driver code
int main()
{
int l = 3, m = 2, x = 4, y = 2;
if (isPossible(l, m, x, y))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation of the approach
class sol
{
// Function that returns true if it is possible to
// make a binary string consisting of l 0's, m 1's,
// x "01" sub-sequences and y "10" sub-sequences
static boolean isPossible(int l, int m, int x, int y)
{
if (l * m == x + y)
return true;
return false;
}
// Driver code
public static void main(String args[])
{
int l = 3, m = 2, x = 4, y = 2;
if (isPossible(l, m, x, y))
System.out.print("Yes");
else
System.out.print("No");
}
}
// This code is contributed by Arnab Kundu
Python3
# Python3 implementation of the approach
# Function that returns true if it is possible to
# make a binary string consisting of l 0's, m 1's,
# x "01" sub-sequences and y "10" sub-sequences
def isPossible(l, m, x, y) :
if (l * m == x + y) :
return True;
return False;
# Driver code
if __name__ == "__main__" :
l = 3; m = 2; x = 4; y = 2;
if (isPossible(l, m, x, y)) :
print("Yes");
else :
print("No");
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class sol
{
// Function that returns true if it is possible to
// make a binary string consisting of l 0's, m 1's,
// x "01" sub-sequences and y "10" sub-sequences
static Boolean isPossible(int l, int m, int x, int y)
{
if (l * m == x + y)
return true;
return false;
}
// Driver code
public static void Main(String []args)
{
int l = 3, m = 2, x = 4, y = 2;
if (isPossible(l, m, x, y))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by Arnab Kundu
输出:
Yes