给定整数N ,它是顶点数。任务是找到可以形成的不同图形的数量。由于答案可能非常大,因此请打印答案%1000000007 。
例子:
Input: N = 3
Output: 8
Input: N = 4
Output: 64
方法:
- 具有N个顶点的图形可包含的最大边数为X = N *(N – 1)/ 2。
- 包含0个边和N个顶点的图形总数为X C 0
- 包含1个边和N个顶点的图形总数为X C 1
- 依此类推,从边数1到具有N个顶点的X
- 因此,可以用n个顶点形成的图的总数将是:
X C 0 + X C 1 + X C 2 +…+ X C X = 2 X。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
const int MOD = 1e9 + 7;
// Function to return (x^y) % MOD
// in O(log(y))
long long power(long long x,
long long y,
const int& MOD)
{
long long res = 1;
while (y > 0) {
if (y & 1)
res = (res * x) % MOD;
x = (x * x) % MOD;
y /= 2;
}
return res;
}
// Function to return the count of distinct
// graphs possible with n vertices
long long countGraphs(int n)
{
// Maximum number of edges for a
// graph with n vertices
long long x = n * (n - 1) / 2;
// Function to calculate
// (2^x) % mod
return power(2, x, MOD);
}
// Driver code
int main()
{
int n = 5;
cout << countGraphs(n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
static final int MOD = (int)1e9 + 7;
// Function to return (x^y) % MOD
// in O(log(y))
static long power(long x,
long y)
{
long res = 1;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % MOD;
x = (x * x) % MOD;
y /= 2;
}
return res;
}
// Function to return the count of distinct
// graphs possible with n vertices
static long countGraphs(int n)
{
// Maximum number of edges for a
// graph with n vertices
long x = n * (n - 1) / 2;
// Function to calculate
// (2^x) % mod
return power(2, x);
}
// Driver code
public static void main (String[] args)
{
int n = 5;
System.out.println(countGraphs(n));
}
}
// This code is contributed by AnkitRai01
Python
MOD = int(1e9 + 7)
# Function to return the count of distinct
# graphs possible with n vertices
def countGraphs(n):
# Maximum number of edges for a
# graph with n vertices
x = (n *( n - 1 )) //2
# Return 2 ^ x
return (pow(2, x, MOD))
# Driver code
n = 5
print(countGraphs(n))
C#
// C# implementation of the approach
using System;
class GFG
{
static int MOD = (int)1e9 + 7;
// Function to return (x^y) % MOD
// in O(log(y))
static long power(long x, long y)
{
long res = 1;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % MOD;
x = (x * x) % MOD;
y /= 2;
}
return res;
}
// Function to return the count of distinct
// graphs possible with n vertices
static long countGraphs(int n)
{
// Maximum number of edges for a
// graph with n vertices
long x = n * (n - 1) / 2;
// Function to calculate
// (2^x) % mod
return power(2, x);
}
// Driver code
static public void Main ()
{
int n = 5;
Console.Write(countGraphs(n));
}
}
// This code is contributed by ajit.
输出:
1024