给定一个整数L ,它是某棵树的所有顶点的度数之和。任务是找到所有这些不同的树(标记为树)的计数。如果两棵树至少具有一个不同的边缘,则它们是不同的。
例子:
Input: L = 2
Output: 1
Input: L = 6
Output: 16
一个简单的解决方案:一个简单的解决方案是找到所有顶点的度数之和为L的树的节点数。如本文所述,这种树中的节点数为n =(L / 2 + 1) 。
现在的解决方案是形成可以使用n个节点形成的所有标记树。这种方法非常复杂,并且对于较大的n值,无法使用此过程找出树木的数量。
高效的解决方案:高效的解决方案是使用Cayley公式来计算节点数,该公式指出存在n (n – 2)棵树,其中n个标注了顶点。因此,现在代码的时间复杂度降低为O(n) ,可以使用模块化幂运算将其进一步降低为O(logn) 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
#define ll long long int
// Iterative Function to calculate (x^y) in O(log y)
ll power(int x, ll y)
{
// Initialize result
ll res = 1;
while (y > 0) {
// If y is odd, multiply x with result
if (y & 1)
res = (res * x);
// y must be even now
// y = y / 2
y = y >> 1;
x = (x * x);
}
return res;
}
// Function to return the count
// of required trees
ll solve(int L)
{
// number of nodes
int n = L / 2 + 1;
ll ans = power(n, n - 2);
// Return the result
return ans;
}
// Driver code
int main()
{
int L = 6;
cout << solve(L);
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG
{
// Iterative Function to calculate (x^y) in O(log y)
static long power(int x, long y)
{
// Initialize result
long res = 1;
while (y > 0)
{
// If y is odd, multiply x with result
if (y==1)
res = (res * x);
// y must be even now
// y = y / 2
y = y >> 1;
x = (x * x);
}
return res;
}
// Function to return the count
// of required trees
static long solve(int L)
{
// number of nodes
int n = L / 2 + 1;
long ans = power(n, n - 2);
// Return the result
return ans;
}
// Driver code
public static void main (String[] args)
{
int L = 6;
System.out.println (solve(L));
}
}
// This code is contributed by ajit.
Python3
# Python implementation of the approach
# Iterative Function to calculate (x^y) in O(log y)
def power(x, y):
# Initialize result
res = 1;
while (y > 0):
# If y is odd, multiply x with result
if (y %2== 1):
res = (res * x);
# y must be even now
#y = y / 2
y = int(y) >> 1;
x = (x * x);
return res;
# Function to return the count
# of required trees
def solve(L):
# number of nodes
n = L / 2 + 1;
ans = power(n, n - 2);
# Return the result
return int(ans);
L = 6;
print(solve(L));
# This code has been contributed by 29AjayKumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Iterative Function to calculate (x^y) in O(log y)
static long power(int x, long y)
{
// Initialize result
long res = 1;
while (y > 0)
{
// If y is odd, multiply x with result
if (y == 1)
res = (res * x);
// y must be even now
// y = y / 2
y = y >> 1;
x = (x * x);
}
return res;
}
// Function to return the count
// of required trees
static long solve(int L)
{
// number of nodes
int n = L / 2 + 1;
long ans = power(n, n - 2);
// Return the result
return ans;
}
// Driver code
static public void Main ()
{
int L = 6;
Console.WriteLine(solve(L));
}
}
// This code is contributed by Tushil.
输出:
16