N people stand in a line, and we numbered them 1,2...n, and now you are asked to rearrange them. The ith people is considred in the front of the (i+1)th, after the rearrange, everyone the people in front of whom can not be the same one as before. How many different strategies you can do the rearrange.
Input:
Each test case just contains one integer, the number of people you have to rearrange.
Output:
The number of strategies you have to rearrange them, with the condition above.
Sample Input:
3 4
Sample Output:
3 11题意:给你一个n,即为n个数,1,2,3,,,,n,问你有多少种排列顺序可以使得每个数前面的的那个数不再是原来的前面的那个数,如:原来是1,2,3,4,5,那么序列5,4,3,2,1就符合要求,而2,1,5,3,4就不行,因为4的前面是3
思路:这题应该是道规律题,那我们就先打个表看看能不能找到规律打表如下
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<queue>
#include<set>
using namespace std;
int main()
{
int a[8]={1,2,3,4,5,6,7,8};
for(int i=1;i<=7;i++)
{
int ans=0;
do
{
bool flag=true;
for(int j=2;j<=i;j++)
if(a[j]-a[j-1]==1)
{
flag=false;
break;
}
if(flag) ans++;
}while(next_permutation(a,a+i));
printf("%d\n",ans);
}
}
//输出 1,1,3,11,53,309,2119
1, 2, 3, 4, 5, 6, 7
1, 1, 3, 11, 53, 309, 2119
规律:a[i]=(i-1)*a[i-1]+(i-2)*(a[i-2])
如果这题单纯的用long long型数据是会爆的,这题需要用大数,java来一发
import java.io.*;
import java.math.*;
import java.util.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
BigInteger a[]=new BigInteger [1001];
a[1]=BigInteger.ZERO;
a[2]=BigInteger.ONE;
a[3]=BigInteger.ONE.multiply(BigInteger.valueOf(3));
for(int i=4;i<=1000;i++)
a[i]=a[i-1].multiply(BigInteger.valueOf(i-1)).add(a[i-2].multiply(BigInteger.valueOf(i-2)));
int t;
Scanner cin=new Scanner(System.in);
while(cin.hasNext())
{
t=cin.nextInt();
System.out.println(a[t]);
}
}
}