1. 程式人生 > >洛谷P1940買蛋糕

洛谷P1940買蛋糕

string 算法 color esp .org nbsp 得出 algorithm urn

  題目傳送門

  題意:給定你一個數n,要求用最小個數的整數組成小於等於n的所有整數,並求出方案數。

  很明顯,擅長二進制的大犇們肯定一眼就看得出方案數是log2(n)+1,然而我並不擅長,但是推了一小會兒也就推出來了,證明也不難。那麽問題就在於怎麽求方案數,我個人使用的深搜,(當然網上有用DP的,然而我一向就不擅長DP(QAQ)),時間限制也放的很寬,有兩秒,我用深搜最慢的點1100ms,也還算比較快了吧(或者是洛谷數據比較水?)反正也很容易了,看代碼自己推一下應該很好懂

#include<cstdio>
#include<cstring>
#include
<cmath> #include<cstdlib> #include<iostream> #include<algorithm> using namespace std; int n,ans,wwy,rei; void dfs(int last,int cnt,int tot) { if(cnt>wwy)return; if(cnt==wwy){ for(int i=min(tot+1,n);i>=last+1;i--) if(tot+i>=n)ans++; else
return; } for(int i=last+1;i<=min(tot+1,n);i++){ int sum=tot+i; dfs(i,cnt+1,sum); } } int main() { std::ios::sync_with_stdio(false); cin>>n;wwy=log2(n)+1;rei=pow(2,wwy-1); cout<<wwy<<" "; if(n<=3){cout<<1;return 0;}//小於3的直接特判退出 dfs(2,3
,3);cout<<ans;
//為什麽從2開始搜呢?因為當n大於1時,1和2必選,這個顯而易見吧
return 0; }

那這道題就這麽WATER掉了~~

(如果有更好的算法歡迎在評論區討論)

洛谷P1940買蛋糕