Rearrange Them ZOJ - 2625(规律,大数)

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]);
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值