hdu3709 Balanced Number 數位dp,hdu3709balanced

來源:互聯網
上載者:User

hdu3709 Balanced Number 數位dp,hdu3709balanced

題意:定義一個數為“balanced number” 當其滿足存在一個數位pos(平衡點),在pos左邊的數位的值乘與pos位的距離值的總和等於右

邊的數位的值乘與pos位的距離值的總和,給定一個區間[l , r],求區間內有多少個balanced number。

思路:設dp[ pos ][ i ][ j ]表示平衡點在i位的情況下,當前考慮pos位,之前已形成的力矩為j(數乘以距離平衡點的距離,在平衡點左

邊的為正,右邊的為負),之後(pos + 1)位於之前位組合使最後平衡(力矩為0)的數的個數,詳見代碼:

/*********************************************************  file name: hdu3709.cpp  author : kereo  create time:  2015年01月24日 星期六 15時27分47秒*********************************************************/#include<iostream>#include<cstdio>#include<cstring>#include<queue>#include<set>#include<map>#include<vector>#include<stack>#include<cmath>#include<string>#include<algorithm>using namespace std;typedef long long ll;const int sigma_size=26;const int N=20;const int MAXN=1500+50;const int inf=0x3fffffff;const double eps=1e-8;const int mod=100000000+7;#define L(x) (x<<1)#define R(x) (x<<1|1)#define PII pair<int, int>#define mk(x,y) make_pair((x),(y))int bit[N]; ll dp[N][N][MAXN]; //dp[pos][i][j]表示在平衡點為i的情況下,當前考慮pos位,之前已形成的力矩為j,之後(pos+1)位與之前位組合使最後平衡的個數ll dfs(int pos,int o,int st,int flag){    if(pos == -1) return st == 0;    if(flag && dp[pos][o][st]!=-1)        return dp[pos][o][st];    int x=flag ? 9 : bit[pos];    ll ans=0;    for(int i=0;i<=x;i++){        int nst=st+(pos-o)*i;        if(nst<0) //力矩為負直接continue            continue;        ans+=dfs(pos-1,o,nst,flag || i<x);    }    if(flag)        dp[pos][o][st]=ans;    return ans;}ll solve(ll x){    int len=0;    if(!x)        bit[len++]=x;    while(x){        bit[len++]=x%10;        x/=10;    }    ll ans=0;    for(int i=0;i<len;i++)        ans+=dfs(len-1,i,0,0);    ans-=len-1; //考慮零的重複計算    return ans;}int main(){    memset(dp,-1,sizeof(dp));    int T;    scanf("%d",&T);    while(T--){        ll n,m;        scanf("%I64d%I64d",&n,&m);        ll ans1= n == 0 ? 0: solve(n-1);        ll ans2=solve(m);        printf("%I64d\n",ans2-ans1);    }return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.