生活随笔
收集整理的這篇文章主要介紹了
HDU多校6 - 6831 Fragrant numbers(dfs爆搜+打表)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個以 " 1145141919 " 無限循環(huán)的字符串,現(xiàn)在可以在合適的位置添加 ' + ' , ' * ' 和 ' ( ' , ' ) ' 將其轉(zhuǎn)換為表達式,現(xiàn)在給出一個 n ,問表達出 n 所需要的最短長度是多少
題目分析:比賽時想到了可以狀壓 3 進制來枚舉每個位置的符號:空格,+,*,然后利用遞歸分治暴力求解,寫完之后因為復雜度不太好把控,循序漸進跑,發(fā)現(xiàn)當字符串長度為 10 的時候就有 4968 個數(shù)了,再想跑 n = 11 的時候就發(fā)現(xiàn)本地跑不出來了,硬著頭皮打了個表交上去竟然 AC 了。。賽后看了一下數(shù)據(jù),發(fā)現(xiàn)詢問數(shù)據(jù)中最大的答案恰好就是 10 ,純運氣選手飄過
當然正解也是可以選擇打表的,只不過打表程序更加優(yōu)秀,其實可以直接使用遞歸分治再加個記憶化,對比我的程序少了個狀壓的過程,具體體現(xiàn)在了分治的過程中
然后因為有很多數(shù)會重復,所以可以用 set 去重,非常方便,dp[ l ][ r ] 為 set<int> 元素,維護了區(qū)間 [ l , r ] 內(nèi)數(shù)字可以組成的答案
時間復雜度不太會算,題解說的是 11^2 * n^2 ,在本地的話反正是秒出就對了
最后對于每個答案的話,其實只有 3 和 7 是需要輸出 -1 的,其余的數(shù)字都是有對應的答案的
代碼:
?
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
#include<unordered_map>
using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=5e3+100;int ans[N];set<int>dp[20][20];string s=" 11451419191145141919";void dfs(int l,int r)
{if(dp[l][r].size())return;if(r-l+1<=4){int num=stoi(s.substr(l,r-l+1));if(num<=5000)dp[l][r].insert(num);}for(int i=l;i<r;i++){dfs(l,i);dfs(i+1,r);for(int x:dp[l][i])for(int y:dp[i+1][r]){if(x+y<=5000)dp[l][r].insert(x+y);if(x*y<=5000)dp[l][r].insert(x*y);}}
}void init()
{memset(ans,-1,sizeof(ans));for(int i=1;i<=11;i++){dfs(1,i);for(int x:dp[1][i])if(ans[x]==-1)ans[x]=i;}
}int main()
{
#ifndef ONLINE_JUDGE
// freopen("data.in.txt","r",stdin);
// freopen("data.out.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);init();int w;cin>>w;while(w--){int n;scanf("%d",&n);printf("%d\n",ans[n]);}return 0;
}
?
總結(jié)
以上是生活随笔為你收集整理的HDU多校6 - 6831 Fragrant numbers(dfs爆搜+打表)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。