BZOJ 1236: SPOJ1433 KPSUM

來源:互聯網
上載者:User

標籤:cst   problem   typedef   串連   script   dao   開頭   數字   blog   

Description

用+-號串連1-n所有數位數位,問結果是多少.

Sol

數位DP.

\(f[i][j][0/1][0/1]\) 表示長度為 \(i\) 的數字,開頭數字是 \(j\) ,是否有前置0(這個會影響符號),每相鄰兩組數符號是否相同.

轉移開一下代碼吧.

這道題的符號有點亂,所以轉移看起來有些亂...其實只有3個狀態,沒前置0,有前置0相鄰兩個數符號相同,有前置0相鄰兩個數符號不同.

沒前置0的只有在第一次統計才會用到.

我發現自己寫數位DP就是寫小於 \(n\) 的,所有都需要將 \(n+1\) 計算...

一開始自己神tm的取了模...

Code
/**************************************************************    Problem: 1236    User: BeiYu    Language: C++    Result: Accepted    Time:0 ms    Memory:1308 kb****************************************************************/ #include <cstdio>#include <iostream>using namespace std; #define debug(a) cout<<#a<<"="<<a<<" "  typedef long long LL;const int N = 25; LL n;LL f[N][N][2][2];// i,j  0/1 qiandao0 0/1 fuhaoLL pow10[N]; void init() {    pow10[0]=1;    for(int i=1;i<=18;i++) pow10[i]=pow10[i-1]*10;    for(int j=0;j<10;j++) {        f[1][j][0][0]=f[1][j-1][0][0]+(j&1 ? 1 : -1)*j;        f[1][j][1][0]=f[1][j][0][0];        f[1][j][1][1]=f[1][j-1][1][1]-j;    }    for(int i=2;i<=18;i++) {        f[i][0][0][0]=f[i-1][9][0][0];        f[i][0][1][0]=-f[i-1][9][1][0];        f[i][0][1][1]=-f[i-1][9][1][1];        for(int j=1;j<10;j++) {            f[i][j][0][0]=f[i][j-1][0][0]-f[i-1][9][1][!(i&1)]-(!(i&1))*j*pow10[i-1];            f[i][j][1][0]=f[i][j-1][1][0]-f[i-1][9][1][0];            f[i][j][1][1]=f[i][j-1][1][1]-f[i-1][9][1][1]-j*pow10[i-1];        }    }     /*  for(int i=1;i<=3;i++) {        for(int j=0;j<10;j++) {            cout<<i<<" "<<j<<":\n";            for(int p=0;p<2;p++) for(int q=0;q<2;q++) debug(f[i][j][p][q]);            cout<<endl;        }    }*/}LL calc(LL x) {    LL g=0,r=0,v=0;    for(int i=18;i;i--) {        if(x/pow10[i-1]) {            if(!g) {                r+=f[i][x/pow10[i-1]-1][0][0];                g=i;            }else {                r+=f[i][x/pow10[i-1]-1][1][!(g&1)]*((g-i)&1 ? -1 : 1);            }            if(g&1){                if((x%pow10[i-1])&1) r+=x/pow10[i-1]*((g-i)&1 ? 1 : -1);            }else {                r+=x/pow10[i-1]*(x%pow10[i-1])*((g-i)&1 ? 1 : -1);            }        }x%=pow10[i-1];    }return r;}int main() {    init();    cin>>n;    cout<<calc(n+1)<<endl;//  while(cin>>n) cout<<calc(n+1)<<endl;    return 0;}

 

BZOJ 1236: SPOJ1433 KPSUM

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.