给定输入集的有序三元组(x,y,z)计数
给定三个整数 N、M 和 P。任务是计算形式为 (x, y, z) 的可能有序三元组的数量,其中
1 ≤ x ≤ N, 1 ≤ y ≤ M and 1 ≤ z ≤ P
由于此计数可能非常大,因此返回模10 9 + 7的答案。
例子:
Input: N = 3, M = 3, P = 3
Output: 6
Explanation: The possible triplets are:
(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)
Input: N = 1, M = 2, P = 3
Output: 1
Explanation: Only one triplet is possible (1, 2, 3)
方法:解决方案基于以下观察。
- Say after sorting the three numbers in ascending order they are A, B and C respectively.
- So there are A choices to choose first element.
- Now this choice is not available for choosing the second one. For second one there are total (B – 1) choices.
- Now these two choices are not available for the last. So there are only (C – 2) choices for third.
- Therefore the total number of possibilities are A * (B – 1) * (C – 2).
按照下面提到的步骤来实施上述观察。
- 按升序对三个输入进行排序。让排序顺序为 (N1, N2, N3)。
- 现在应用从观察得出的公式得到最终答案。
- 返回以 10 9 + 7 为模的最终答案。
下面是上述方法的实现。
C++
// C++ code to implement the above approach
#include
using namespace std;
const unsigned int mod = 1000000007;
// Function to count the
// total number of possible triplets
long long int solve(int N, int M, int P)
{
int nums[] = { N, M, P };
sort(nums, nums + 3);
long long int ans = ((nums[0] *
(nums[1] - 1)) % mod
* (nums[2] - 2) %
mod)% mod;
return ans;
}
// Driver code
int main()
{
int N = 3, M = 3, P = 3;
long long int ans = solve(N, M, P);
cout << ans << endl;
return 0;
}
Java
// Java code to implement the above approach
// Importing Arrays class from the utility class
import java.util.Arrays;
class GFG
{
public static long mod = 1000000007;
// Function to count the
// total number of possible triplets
static long solve(int N, int M, int P)
{
int nums[] = { N, M, P };
Arrays.sort(nums);
long ans = ((nums[0] * (nums[1] - 1)) % mod
* (nums[2] - 2) % mod)
% mod;
return ans;
}
// Driver method
public static void main(String[] args)
{
int N = 3, M = 3, P = 3;
long ans = solve(N, M, P);
System.out.println(ans);
}
}
// This code is contributed by rakeshsahni
Python3
# Python3 program for the above approach
# Function to count the total number of
# possible triplets
def solve(N, M, P):
mod = 1000000007
nums = [ N, M, P ]
nums.sort()
ans = ((nums[0] * (nums[1] - 1)) % mod *
(nums[2] - 2) % mod) % mod
return ans
# Driver Code
if __name__ == "__main__":
N, M, P = 3, 3, 3
ans = solve(N, M, P)
print(ans)
# This code is contributed by Abhishek Thakur.
C#
// C# code to implement the above approach
// Importing Arrays class from the utility class
using System;
class GFG
{
static long mod = 1000000007;
// Function to count the
// total number of possible triplets
static long solve(int N, int M, int P)
{
int []nums = { N, M, P };
Array.Sort(nums);
long ans = ((nums[0] * (nums[1] - 1)) % mod
* (nums[2] - 2) % mod) % mod;
return ans;
}
// Driver method
public static void Main()
{
int N = 3, M = 3, P = 3;
long ans = solve(N, M, P);
Console.Write((ans));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
6
时间复杂度: O(1)
辅助空间: O(1)