日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

1049 Counting Ones (30 分)【难度: 难 / 知识点: 分治 / DP】

發布時間:2025/3/20 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 1049 Counting Ones (30 分)【难度: 难 / 知识点: 分治 / DP】 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.


https://pintia.cn/problem-sets/994805342720868352/problems/994805430595731456
方法一: 找規律,分治做法。

//0-999 n //0-1999 1000+2*n 0-999=n 1000-1999只看千位1000個 1001-1999 不看千位 n個 //0-2999 1000+3*n //0-3999 1000+4*n; //0-4999 1000+5*n; //0-9999 1000+10*n;//0-9999 n //0-19999 n*2+10000;//2500 == 1000+2*n+f(500) //1234 == (b[i]+1)+dfs(n-a[i])+(n-a[i]) #include<bits/stdc++.h> using namespace std; int a[]={1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000}; int b[]={0, 1, 20, 300, 4000, 50000, 600000, 7000000, 80000000, 900000000}; int dfs(int n) {if(n==0) return 0;int i=0,j=0;while(n/a[i]>9) i++;j=n/a[i];//首位 if(j==1) return b[i]+1+dfs(n-a[i])+(n-a[i]);else return b[i]*j+a[i]+dfs(n-j*a[i]); } int main(void) {int n; cin>>n;cout<<dfs(n)<<endl; }

這道題的正解其實是數位DP,是一道非常經典的數位DP板子題
方法二: 數位DP

/*001~abc-1, 999abc1. num[i] < x, 02. num[i] == x, 0~efg3. num[i] > x, 0~999*/ #include<bits/stdc++.h> using namespace std; int get(vector<int> nums,int l,int r) {int res=0;for(int i=l;i>=r;i--) res=res*10+nums[i];return res; } int count(int n,int x) {vector<int>num;while(n) num.push_back(n%10),n/=10;n=num.size();int res=0;for(int i=n-1-!x;i>=0;i--)//處理特殊的情況例如 10 當我們處理1時零的個數 00-09 是10種情況這顯然不對{if(i<n-1)//從第二位,開始算前面的{res+=get(num,n-1,i+1)*pow(10,i);//默認當前的值不是0,那么有0-abc-1這樣的一共這么多種if(x==0) res-=pow(10,i);//如果當前位是0,那么得減去前導零的情況}if(num[i]==x) res+=get(num,i-1,0)+1;//加1的目的是有全0的情況else if(num[i]>x) res+=pow(10,i);}return res; } int main(void) {int n; cin>>n;cout<<count(n,1);return 0; }

總結

以上是生活随笔為你收集整理的1049 Counting Ones (30 分)【难度: 难 / 知识点: 分治 / DP】的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。