题解:P11362 [NOIP2024] 遗失的赋值

· · 题解

对于相邻的 c_i 和 c_{i+1},考虑 c_i\le j < c_{i+1} 的 a_j,b_j 合法选法数量。如果我们求出来了这些,乘起来就可以得到答案了(当然还有两头的,不过那些很好求)。

正难则反,考虑不合法的选法数量,我们发现不合法的选法中:

中间都是这个规律,直到:

设 l=c_{i+1}-c_i,这个过程中,“随意”的变量有 l-1 个,还有一个只要满足不等即可,因此总的方案数量为 v^{l-1}(v-1)。

算出了不合法数量,用 v^{2l} 减去不合法数量就得到了合法数量。然后求出每个 1\le i <m 的合法数量的乘积,就得到了中间部分的答案。

算出了中间部分,开头结尾也是很好算的(自由变量随便取就行),算出来之后和中间部分乘起来,就得到了答案。

这个过程可以用快速幂实现,时间复杂度 O(Tm \log n)。

实现的时候记得特判无解。

#include<bits/stdc++.h>
#define int long long
#define N 100005
using namespace std;
const int mod=1e9+7;
int T,n,m,v;
struct node{
    int c,d;
}a[N];
int cmp(node a,node b){
    if(a.c!=b.c)return a.c<b.c;
    return a.d<b.d;
}
int qpow(int x,int y){
    int ans=1;
    while(y){
        if(y&1)ans=ans*x%mod;
        x=x*x%mod;y>>=1;
    }
    return ans;
}
signed main(){
    cin>>T;
    while(T--){
        cin>>n>>m>>v;int f=0;
        for(int i=1;i<=m;++i)scanf("%lld%lld",&a[i].c,&a[i].d);
        sort(a+1,a+m+1,cmp);
        for(int i=1;i<m;++i){
            if(a[i].c==a[i+1].c&&a[i].d!=a[i+1].d)f=1;
        }
        if(f){
            cout<<"0\n";continue;
        }
        int ans=qpow(v,(a[1].c-1)*2);
        for(int i=1;i<m;++i){
            if(a[i].c==a[i+1].c)continue;
            ans=ans*(qpow(v,(a[i+1].c-a[i].c)*2)-qpow(v,a[i+1].c-a[i].c-1)*(v-1)%mod+mod)%mod;
        }
        ans=ans*qpow(v,(n-a[m].c)*2)%mod;
        cout<<ans<<'\n';
    }
    return 0;
}