【組合數+找規律】codeforces 815B - Karen and Test

CN_swords發表於2017-07-27

Link:http://codeforces.com/problemset/problem/815/B

/*
題意: 給出一個n長度的序列,按op +,- 交換得到下一行序列,直到變成一個數字,求這個數字的值。【具體看Note】
題解: 發現在n為偶數時,n-1個數形成的倒三角,是隔個位相加和,其係數為組合數,例n=4時,前三個的倒三角的末端值為a1+a3,若n=6時,前5個倒三角末端值為a1+2a3+a5,同理。那麼n=4的末端值是a1a2a3和a2a3a4的倒三角的差值,n=6的末端值是a1a2a3a4a5和a2a3a4a5a6的倒三角的和值,所以分類n%4==0 和n%4 == 1。
那n為奇數時,先算一層,其實符號還是從正開始的,在依上計算。特判n=1,n=2,n=3。
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;

const int N = 200005;
const int mod = 1e9+7;
LL a[N];
LL powz[N],inv[N],powinv[N];

void init(){
    powz[0] = 0; powz[1] = 1;
    inv[0] = 0; inv[1] = 1;
    powinv[0] = 0; powinv[1] = 1;
    for(int i = 2; i < N; i++){
        powz[i] = (powz[i-1]*(LL)i)%mod;
        inv[i] = inv[mod%i]*(mod-mod/i)%mod;
        powinv[i] = powinv[i-1]*inv[i]%mod;
    }
}
LL C(int x, int y){
    if(x == 0 || x == y)    return 1LL;
    return powz[y]*powinv[y-x]%mod*powinv[x]%mod;
}


int main(){
    init();
    int n;
    scanf("%d",&n);
    for(int i = 1; i <= n; i++)
        scanf("%I64d",&a[i]);
    if(n == 1){
        printf("%I64d\n",a[1]);
        return 0;
    }
    if(n&1){
        LL pre = a[1];
        LL op = 1;
        for(int i = 2; i <= n; i++){
            a[i-1] = (pre+op*a[i]+mod)%mod;
            pre = a[i];
            op *= -1;
        }
        n--;
    }
    if(n == 2){
        printf("%I64d\n",(a[1]+a[2])%mod);
        return 0;
    }
    int ff = n/2-1;
    LL ans1 = 0, ans2 = 0;
    int k = 0, flag = 0;
    for(int i = 1; i <= n; i+=2){
        ans1 = (ans1+a[i]*C(k,ff)%mod)%mod;
        if(k == ff)
            flag = 1;
        if(flag)
            k--;
        else
            k++;
    }
    k = 0 , flag = 0;
    for(int i = 2; i <= n; i+=2){
        ans2 = (ans2+a[i]*C(k,ff)%mod)%mod;
        if(k == ff)
            flag = 1;
        if(flag)
            k--;
        else
            k++;
    }
    if(n%4 == 0){
        printf("%I64d\n",(ans1-ans2+mod)%mod);
    }
    else{
        printf("%I64d\n",(ans1+ans2)%mod);
    }
    return 0;
}


相關文章