给定两个正整数n,k 。考虑一个完整连接图中n个节点的无向完整连接图。任务是计算可以从任何节点开始并通过访问K个节点返回该节点的方式的数目。
例子:
Input : n = 3, k = 3
Output : 2
Input : n = 4, k = 2
Output : 3
令f(n,k)为一个函数,该函数返回可以从任何节点开始并通过访问K个节点返回的方式的数目。
如果我们从一个节点开始和结束,那么对于中间节点,我们将有K – 1个选择,因为我们已经在开始时选择了一个节点。对于每个中间选择,您都有n – 1个选项。因此,这将产生(n – 1) k – 1,但是随后我们必须删除所有导致较小循环的选择,因此我们减去f(n,k – 1) 。
因此,递归关系变为
f(n,k)=(n – 1) k – 1 – f(n,k – 1),基本情况为f(n,2)= n – 1。
在扩展时,
f(n,k)=(n – 1) k – 1 –(n – 1) k – 2 +(n – 1) k – 3 …..(n – 1)(例如等式1)
将f(n,k)除以(n – 1),
f(n,k)/(n – 1)=(n – 1) k – 2 –(n – 1) k – 3 +(n – 1) k – 4 ….. 1(等式2)
在添加eqn 1和eqn 2时
f(n,k)+ f(n,k)/(n – 1)=(n – 1) k – 1 +( -1 ) k
f(n,k)*((n -1)+1)/(n – 1)=(n – 1) k – 1 +( -1 ) k
以下是此方法的实现:
C++
// C++ Program to find number of cycles of length
// k in a graph with n nodes.
#include
using namespace std;
// Return the Number of ways from a
// node to make a loop of size K in undirected
// complete connected graph of N nodes
int numOfways(int n, int k)
{
int p = 1;
if (k % 2)
p = -1;
return (pow(n - 1, k) + p * (n - 1)) / n;
}
// Driven Program
int main()
{
int n = 4, k = 2;
cout << numOfways(n, k) << endl;
return 0;
}
Java
// Java Program to find number of
// cycles of length k in a graph
// with n nodes.
public class GFG {
// Return the Number of ways
// from a node to make a loop
// of size K in undirected
// complete connected graph of
// N nodes
static int numOfways(int n, int k)
{
int p = 1;
if (k % 2 != 0)
p = -1;
return (int)(Math.pow(n - 1, k)
+ p * (n - 1)) / n;
}
// Driver code
public static void main(String args[])
{
int n = 4, k = 2;
System.out.println(numOfways(n, k));
}
}
// This code is contributed by Sam007.
Python3
# python Program to find number of
# cycles of length k in a graph
# with n nodes.
# Return the Number of ways from a
# node to make a loop of size K in
# undirected complete connected
# graph of N nodes
def numOfways(n,k):
p = 1
if (k % 2):
p = -1
return (pow(n - 1, k) +
p * (n - 1)) / n
# Driver code
n = 4
k = 2
print (numOfways(n, k))
# This code is contributed by Sam007.
C#
// C# Program to find number of cycles
// of length k in a graph with n nodes.
using System;
class GFG {
// Return the Number of ways from
// a node to make a loop of size
// K in undirected complete
// connected graph of N nodes
static int numOfways(int n, int k)
{
int p = 1;
if (k % 2 != 0)
p = -1;
return (int)(Math.Pow(n - 1, k)
+ p * (n - 1)) / n;
}
// Driver code
static void Main()
{
int n = 4, k = 2;
Console.Write( numOfways(n, k) );
}
}
// This code is contributed by Sam007.
PHP
Javascript
输出:
3