定义:
一个n的全排列A[i]是单峰的,当且仅当存在某个x使得A[1]<A[2]<…<A[x]>A[x+1]>…>A[n]
例如,对于9的全排列,125798643是一个单峰排列,123456789也是一个单峰排列,但356298741就不是。
那么如何求n的单峰全排列的个数?
首先明确一点:n必须是“山峰”的最高点,然后依次是n-1,n-2,…,1。其中,n-1这个数可以放在左边的“山”,也可以放在右边的“山”,然后n-2亦是如此……直到1,都有两种放置方案,故最后的结果就是2^(n-1)。
比如 n=9,然后9放好后,考虑8是放在9左侧还是右侧,在考虑7是放在9的左侧还是右侧,… 直到1,最终为2^8
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Consider a permutation p of length n, we build a graph of size n using it as follows:
For every 1≤i≤n, find the largest j such that 1≤jpi, and add an undirected edge between node i and node j
For every 1≤i≤n, find the smallest j such that i<j≤n and pj>pi, and add an undirected edge between node i and node j
In cases where no such j exists, we make no edges. Also, note that we make edges between the corresponding indices, not the values at those indices.
For clarity, consider as an example n=4, and p=[3,1,4,2]; here, the edges of the graph are (1,3),(2,1),(2,3),(4,3).
A permutation p is cyclic if the graph built using p has at least one simple cycle.
Given n, find the number of cyclic permutations of length n. Since the number may be very large, output it modulo 109+7.
Please refer to the Notes section for the formal definition of a simple cycle
Input
The first and only line contains a single integer n (3≤n≤106).
Output
Output a single integer 0≤x<109+7, the number of cyclic permutations of length n modulo 109+7.
题意: 给一个 n 的全排列,然后构建一个图,节点为每个数的下标,数组中的每个数可以与右边第一个大于它的数,左边第一个大于它的数连接无向边,问在 n 的全排列中有多少排列构成的图中存在简单环。
思路:当一个数左右两边存在大于这个数的数,必定能构成一个简单环,例如:对于i , j , k , 当 i > j , k > j ,接下来不管是 i 和 k 谁比较大,这三个点都能连接成简单环,所以只要不存在类似的波谷结构就不存在环,那就是单峰序列了,即峰顶为 n 其他数下降的排列在左右,这种情况必然不可能存在环,又因为单峰序列有 2^(n-1) 个 ,因此最终答案就是 n! - 2 ^ (n-1)
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
ll mod=1000000007;
ll n;
cin>>n;
ll sum=1;
for(int i=2;i<=n;i++)
{
sum*=i;
sum%=mod;
}
ll t=1;
for(int i=2;i<=n;i++)
{
t*=2;
t%=mod;
}
ll ans=(sum-t+mod)%mod;
cout<<ans<<endl;
}