hdu 1455 sticks(經典深搜+剪枝技巧)

來源:互聯網
上載者:User

標籤:搜尋   dfs   



題意:有一堆的木棒,長度不一,它們是有一些整齊的木棒截斷而成的,求最小的木棒原始長度。

思路很簡單深搜,但是直接深搜的話會tle,首先可以對木棒長度進行排序從大到小,優先使用長度長的木棒,加入當前長度不符合,考慮下一個木棒

其次如果長度為零的時候選擇木棒失敗,那麼直接退出,實測加上這一剪枝就可以ac,這一剪枝可以協助我們儘可能的在靠近樹根處剪枝,所以最佳化效果很明顯。

然後是如果這次選擇的木棒長度和上次失敗時的一樣,那麼剪枝。

#include<cstdio>  #include<cstring>  #include<cmath>  #include<cstdlib>  #include<iostream>  #include<algorithm>  #include<vector>  #include<map>  #include<queue>  #include<stack> #include<string>#include<map> #include<set>#define eps 1e-6 #define LL long long  using namespace std;  const int maxn = 70;const int INF = 0x3f3f3f3f;int n, sumv, target, aim;//target表示目標的棍子個數,aim表示目標的棍子長度 int stick[maxn], vis[maxn];bool cmp(int a, int b) {return a > b;}void init() {sumv = 0;for(int i = 0; i < n; i++) {cin >> stick[i]; sumv += stick[i];}sort(stick, stick+n, cmp);}bool dfs(int cnt, int len, int pos) {if(cnt == target) return true;if(len == aim) return dfs(cnt+1, 0, 0); for(int i = pos; i < n; i++) {                         //從大到小排序後,按順序搜尋 if(!vis[i] && len+stick[i] <= aim) {vis[i] = 1;if(dfs(cnt, len+stick[i], i+1)) return true;vis[i] = 0;                                     if(len == 0) return false;                     //如果第一根時失敗剪枝 while(i+1 < n && stick[i+1] == stick[i]) i++;  //如果下一根長度跟當前的失敗的長度一樣,剪枝 }}return false;}void solve() {int ans = 0;for(int i = 1; i <= sumv; i++) if(sumv % i == 0) {memset(vis, 0, sizeof(vis));aim = i; target = sumv / aim;if(dfs(0, 0, 0)) {ans = aim; break;}}cout << ans << endl;}int main() {//freopen("input.txt", "r", stdin);while(scanf("%d", &n) == 1 && n) {init();solve();}return 0;}

hdu 1455 sticks(經典深搜+剪枝技巧)

聯繫我們

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