给定整数N,任务是根据以下条件从可以形成无环图的范围[1,N]中查找整数的排列数目:
- 对于每1≤i≤N ,找到最大j ,使1≤j 且A [j]> A [i ],并在节点i和节点j之间添加无向边。
- 对于每1≤i≤N ,找到最小的j ,使i
且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
是数组的索引,则如果A [i]> A [j]和A [j] ,则将存在是由边{ [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
8
时间复杂度:O(logN)
空间复杂度:O(1)