標籤: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