标签:des style http color java os io strong
1 100 -1
12 11
把斐波那契数列插入ac自动机,然后数位dp进行二分查找,
代码:
/* *********************************************** Author :rabbit Created Time :2014/8/15 16:27:37 File Name :3.cpp ************************************************ */ #pragma comment(linker, "/STACK:102400000,102400000") #include <stdio.h> #include <iostream> #include <algorithm> #include <sstream> #include <stdlib.h> #include <string.h> #include <limits.h> #include <string> #include <time.h> #include <math.h> #include <queue> #include <stack> #include <set> #include <map> using namespace std; #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) typedef long long ll; struct Trie{ ll next[1010][10],end[1010],fail[1010]; ll root,L; void init(){ L=0; root=newnode(); } ll newnode(){ for(ll i=0;i<10;i++) next[L][i]=-1; end[L++]=0; return L-1; } void insert(ll x){ ll a[15],len=0; while(x){ a[len++]=x%10; x/=10; } //for(ll i=len-1;i>=0;i--)cout<<a[i]<<" ";cout<<endl; ll now=root; for(ll i=len-1;i>=0;i--){ if(next[now][a[i]]==-1) next[now][a[i]]=newnode(); now=next[now][a[i]]; } end[now]=1; } void build(){ queue<ll> Q; fail[root]=root; for(ll i=0;i<10;i++) if(next[root][i]==-1) next[root][i]=root; else{ fail[next[root][i]]=root; Q.push(next[root][i]); } while(!Q.empty()){ ll now=Q.front(); Q.pop(); end[now]|=end[fail[now]]; for(ll i=0;i<10;i++) if(next[now][i]==-1) next[now][i]=next[fail[now]][i]; else{ fail[next[now][i]]=next[fail[now]][i]; Q.push(next[now][i]); } } } }ac; ll fib[60],dp[15][1010],seq[60],POW[20]; ll suf[15],num[15]; ll dfs(ll pos,ll st,bool flag){ if(pos==0)return 0; if(flag&&dp[pos][st]!=-1)return dp[pos][st]; ll u=flag?9:num[pos]; ll ans=0; for(ll i=0;i<=u;i++){ ll state=ac.next[st][i]; if(ac.end[state]){ if(flag||i<u)ans+=POW[pos-1];//后面的任意取 else ans+=suf[pos-1]+1; } else ans+=dfs(pos-1,state,flag||i<u); } if(flag)dp[pos][st]=ans; return ans; } ll cal(ll x){ ll len=0; suf[0]=0; //cout<<"x="<<x<<endl; while(x){ num[++len]=x%10; suf[len]=suf[len-1]+x%10*POW[len-1]; x/=10; } //cout<<"suf: ";for(ll i=1;i<=len;i++)cout<<suf[i]<<" ";cout<<endl; return dfs(len,ac.root,0); } int main() { //freopen("data.in","r",stdin); //freopen("data1.out","w",stdout); fib[1]=1; fib[2]=1; for(ll i=3;i<=60;i++) fib[i]=fib[i-1]+fib[i-2]; memset(dp,-1,sizeof(dp)); ac.init(); for(ll i=1;i<=56;i++) if(fib[i]>10)ac.insert(fib[i]); POW[0]=1; for(ll i=1;i<=15;i++)POW[i]=10*POW[i-1]; ac.build(); for(ll i=2;i<=56;i++){ ll l=13,r=POW[12]; while(l<r){ ll mid=(l+r)/2; ll ret=cal(mid); // cout<<"han "<<i<<" "<<l<<" "<<r<<" "<<ret<<endl; if(ret<fib[i])l=mid+1; else r=mid; } seq[i]=l; } //for(ll i=2;i<=56;i++)cout<<seq[i]<<endl;return 0; ll n; while(cin>>n&&n!=-1){ ll ans=1e15; for(ll i=2;i<=56;i++){ ll tt=n-seq[i]; if(tt<0)tt=-tt; ans=min(ans,tt); } cout<<ans<<endl; } return 0; }
HDU 4518 ac自动机+数位dp,布布扣,bubuko.com
标签:des style http color java os io strong
原文地址:http://blog.csdn.net/xianxingwuguan1/article/details/38588757