2019 Multi-University Training Contest 5 permutation 2

permutation 2

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1458 Accepted Submission(s): 688

Problem Description

You are given three positive integers N,x,y.
Please calculate how many permutations of 1∼N satisfies the following conditions (We denote the i-th number of a permutation by pi):

  1. p1=x

  2. pN=y

  3. for all 1≤i<N, |pi−pi+1|≤2

Input

The first line contains one integer T denoting the number of tests.

For each test, there is one line containing three integers N,x,y.

  • 1≤T≤5000

  • 2≤N≤105

  • 1≤x<y≤N

Output

For each test, output one integer in a single line indicating the answer modulo 998244353.

Sample Input

3
4 1 4
4 2 4
100000 514 51144

Sample Output

2
1
253604680

题意

已知有 n 个连续的数 1-n,第一位数固定为 x ,最后一位数为 y, 保证相邻的数之间差值不超过 2 ,问一共有多少种排列。

分析

先考虑最简单的第一位是1,最后一位是 n 的情况,当n在最后一位时,有两种情况:
1 ············· (n - 1) n //相当于1-(n-1)的所有情况
1 ············ (n-3) (n-1)(n-2) n //相当于1-(n-3)的所有情况
所以 a[n]= a[n-1] + a[n-3]
找到递推式,我们就可以计算出结果了
要注意的是,a[n]不仅仅可以代表1-n的排列,同样,它也可以代表n个连续的数的排列。
当第一位数是 x 的时候,我们发现从x 到 1 再到 x+1 都是固定的顺序,这样,就减少了以为可移动的数字;
当最后一位数是y的时候,我们发现从y- 1到 n 到 y 的顺序也是固定的,也减少了一位数。
所有的情况都考虑了,那么,最终连续的数有多少个就直接输出之前打表计算好的值即可。

代码

#include<bits/stdc++.h> 
using namespace std;

long long a[100005]; 
const long long mod=998244353;

int main()
{
   a[0]=0;a[1]=1;a[2]=1;a[3]=1; 
   for(int i=4;i<=100005;i++)
       a[i]=(a[i-1] +a[i-3] )%mod;
   int t;
   cin>>t;
   while(t--)
   {
       int n,x,y;
       scanf("%d%d%d",&n,&x,&y);
       long long ans=y-x+1;
       if(x!=1) ans--;
       if(y!=n) ans--; 
   	cout<<a[ans]<<endl;
   }
   return 0;
}

参考:
https://blog.csdn.net/youth666/article/details/98622954#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值