给定一个整数N,任务是根据以下条件,从[1, N]范围内找到可以形成无环图的整数的排列数:
- 对于每一个1 ≤ i ≤ N ,找到最大的j使得1 ≤ j < i和A[j] > A[i ],并在节点i和节点j之间添加一条无向边。
- 对于每个1 ≤ i ≤ N ,找到最小的j使得i < j ≤ N和A[j] > A[i] ,并在节点i和节点j之间添加一条无向边。
例子:
Input: 3
Output: 4
Explanation:
{1, 2, 3}: Possible (Graph Edges : { [1, 2], [2, 3] }. Therefore, no cycle exists)
{1, 3, 2}: Possible (Graph Edges : { [1, 3], [2, 3] }. Therefore, no cycle exists)
{2, 1, 3}: Not possible (Graph Edges : { [2, 3], [1, 3], [1, 2] }. Therefore, cycle exists)
{2, 3, 1}: Possible (Graph Edges : { [2, 3], [1, 3] }. Therefore, no cycle exists)
{3, 1, 2}: Not possible (Graph Edges : { [1, 2], [1, 3], [2, 3] }. Therefore, cycle exists)
{3, 2, 1}: Possible (Graph Edges : { [2, 3], [1, 2] }. Therefore, no cycle exists)
Input : 4
Output : 8
处理方法:按照以下步骤解决问题:
- 一共有N个!可以生成由范围[1, N] 中的整数排列组成的可能数组。
- 根据给定的条件,如果i, j, k (i < j < k)是来自数组的索引,那么如果A[i] > A[j]和A[j] < A[k] ,那么将有是一个由边 { [A[j], A[i]], [A[j], A[k]], [A[i], A[k]]}组成的循环。
- 除去这些排列,剩下 2 (N – 1) 个可能的排列。
- 剩余的排列仅给出[1, N – 1]范围内整数的两个可能位置和N 的1 个可能位置。
Illustration:
For N = 3:
Permutation {2, 1, 3} contains a cycle as A[0] > A[1] and A[1] < A[2].
Permutation {3, 1, 2} contains a cycle as A[0] > A[1] and A[1] < A[2].
All remaining permutations can generate an acyclic graph.
Therefore, the count of valid permutations = 3! – 2 = 4 = 23 – 1
- 因此,打印2 N – 1作为所需答案。
下面是上述方法的实现:
C++
// C++ implementation of above approach
#include
using namespace std;
// Find the count of possible graphs
void possibleAcyclicGraph(int N)
{
cout << pow(2, N - 1);
return;
}
// Driver Code
int main()
{
int N = 4;
possibleAcyclicGraph(N);
return 0;
}
Java
// Java implementation of
// the above approach
import java.util.*;
class GFG{
// Find the count of
// possible graphs
static void possibleAcyclicGraph(int N)
{
System.out.print((int)Math.pow(2,
N - 1));
return;
}
// Driver Code
public static void main(String[] args)
{
int N = 4;
possibleAcyclicGraph(N);
}
}
// This code is contributed by Princi Singh
Python3
# Python3 implementation of above approach
# Find the count of possible graphs
def possibleAcyclicGraph(N):
print(pow(2, N - 1))
return
# Driver code
if __name__ == '__main__':
N = 4
possibleAcyclicGraph(N)
# This code is contributed by mohit kumar 29
C#
// C# implementation of
// the above approach
using System;
class GFG{
// Find the count of
// possible graphs
static void possibleAcyclicGraph(int N)
{
Console.Write((int)Math.Pow(2, N - 1));
return;
}
// Driver Code
public static void Main()
{
int N = 4;
possibleAcyclicGraph(N);
}
}
// This code is contributed by sanjoy_62
Javascript
8
时间复杂度:O(logN)
空间复杂度:O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live