permutation 2(HDU-6630)

本文探讨了在特定约束条件下,即序列首尾元素固定且相邻元素差值不超过2的情况下,求解1到N整数的所有可能排列数量的算法。通过观察规律,采用动态规划方法,实现了高效求解,并针对特殊情况进行了讨论。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题意:给出 t 组数据,每组给出一个 n,代表有 1~n 的数,再给出 x、y,代表 p[1]=x,p[n]=y,现已知 |p[i]-p[i+1]|<=2,问有多少中排列方式

思路:

打个表,可以发现规律为,对于 y-x,有:dp[0]=0,dp[1]=1,dp[2]=1,dp[3]=1,dp[i]=dp[i-1]+dp[i-3]

然后特判一下 x=1&&y=n、x=1、y=n 的三种情况即可 

Source Program

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<unordered_map>
#include<bitset>
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
#define Pair pair<int,int>
LL quickPow(LL a,LL b){ LL res=1; while(b){if(b&1)res*=a; a*=a; b>>=1;} return res; }
LL multMod(LL a,LL b,LL mod){ a%=mod; b%=mod; LL res=0; while(b){if(b&1)res=(res+a)%mod; a=(a<<=1)%mod; b>>=1; } return res%mod;}
LL quickPowMod(LL a, LL b,LL mod){ LL res=1,k=a; while(b){if((b&1))res=multMod(res,k,mod)%mod; k=multMod(k,k,mod)%mod; b>>=1;} return res%mod;}
LL getInv(LL a,LL mod){ return quickPowMod(a,mod-2,mod); }
LL GCD(LL x,LL y){ return !y?x:GCD(y,x%y); }
LL LCM(LL x,LL y){ return x/GCD(x,y)*y; }
const double EPS = 1E-10;
const int MOD = 998244353;
const int N = 100000+5;
const int dx[] = {-1,1,0,0,1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;

LL dp[N];
int init() {
    dp[0] = 0;
    dp[1] = 1;
    dp[2] = 1;
    dp[3] = 1;
    for (int i = 4; i <= 100000; i++)
        dp[i] = ((dp[i - 1] + dp[i - 3]) % MOD);
}
int main() {
    init();
    int t;
    scanf("%d", &t);
    while (t--) {
        LL n, x, y;
        scanf("%lld%lld%lld", &n, &x, &y);
        if (x == 1 && y == n)
            printf("%d\n", dp[y - x + 1]);
        else if (x == 1)
            printf("%d\n", dp[y - x]);
        else if (y == n)
            printf("%d\n", dp[y - x]);
        else
            printf("%d\n", dp[y - x - 1]);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值