📌  相关文章
📜  给定输入集的有序三元组(x,y,z)计数

📅  最后修改于: 2022-05-13 01:56:06.752000             🧑  作者: Mango

给定输入集的有序三元组(x,y,z)计数

给定三个整数 N、M 和 P。任务是计算形式为 (x, y, z) 的可能有序三元组的数量,其中

由于此计数可能非常大,因此返回模10 9 + 7的答案。

例子:

方法:解决方案基于以下观察。

按照下面提到的步骤来实施上述观察。

  • 按升序对三个输入进行排序。让排序顺序为 (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)