zhx's contest

Time Limit: 1000 ms / MemoryLimit: 65536 kb

Description

As one of the most powerfulbrushes, zhx is required to give his juniors $n$ problems.
zhx thinks the $i^{th}$ problem's difficulty is $i$. He wants to arrange theseproblems in a beautiful way.
zhx defines a sequence $\{a_{i}\}$ beautiful if there is an $i$ that matchestwo rules below:
1: $a_{1} .. a_{i}$ are monotone decreasing or monotone increasing.
2: $a_{i} .. a_{n}$ are monotone decreasing or monotone increasing.

He wants you to tell him that how many permutations of problems are there ifthe sequence of the problems' difficulty is beautiful.
zhx knows that the answer may be very huge, and you only need to tell him theanswer module $p$.

Input

Multiply test cases(less than $1000$).Seek $EOF$ as the end of the file.
For each case, there are two integers $n$ and $p$ separated by a space in aline. ($1 \leq n,p \leq 10^{18}$)

Output

For each test case, output asingle line indicating the answer.

Sample Input

2 233

3 5

Sample Output

2

1

 

Hint

In the firstcase, both sequence {1, 2} and {2, 1} are legal.

In the secondcase, sequence {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}are legal, so the answer is 6 mod 5 = 1

 

Source

BestCoder Round #33


 

分析:

数字1到n的全排列问题

 

限制条件为:

1: a1..ai are monotone decreasing or monotone increasing.
2: ai..an are monotone decreasing or monotoneincreasing.

考虑:

a.     全递增/全递减

b.     先增→ai→再减(ai(max)=n

把n放在任意位置,除了n剩余的数都有两种排法:ai左边或者ai右边故:2^(n—1),其中包括了情况a的两种(n在第一个位置和n在最后一个位置  故减去后:2^(n-1)-2

 

c.   先减→ai→再增 ai(min)=1

除了ai剩余的数都有两种排法:ai左边或者ai右边故:2^(n—1),其中包括了情况a的两种,减去后:2^(n-1)-2


总:a+b+c=2+2^n-4=2^n-2 种

答案:(2^n-2 )%p

注意特殊情况,当n=1,输出1;当p=1,输出0


#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long ll;
ll mod;
ll mul_mod(ll a, ll n)  //快速乘取模
{
	ll ans = 0;
	while (n)
	{
		if (n & 1) ans = (ans + a) % mod;
		a = (a + a) % mod;
		n /= 2;
	}
	return ans;
}
ll pow_mod(ll a, ll n)  //快速幂取模
{
	ll ans = 1;
	while (n)
	{
		if (n & 1) ans = mul_mod(ans, a);
		a = mul_mod(a, a);
		n >>= 1;
	}
	return ans;
}
int main()
{
	long long n;
	while (~scanf("%lld %lld", &n, &mod))
	{
		if (n == 1)
		{
			if (mod == 1) printf("0\n");
			else printf("1\n");
		}
		else printf("%lld\n", (pow_mod(2, n) - 2 + mod) % mod);
	}
	return 0;
}


快速幂取模:http://blog.csdn.net/paradoxo/article/details/74936496

快速乘取模:http://blog.csdn.net/paradoxo/article/details/74936435









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值