搜索--子集和
一個整數數組,長度為n,將其分為m份,使各份的和相等,求m的最大值
??比如{3,2,4,3,6} 可以分成{3,2,4,3,6} m=1; ?
??{3,6}{2,4,3} m=2
??{3,3}{2,4}{6} m=3 所以m的最大值為3
解:poj 1011,搜索+強剪枝
Description
George took sticks of the same length and cut them randomly until all parts became at most 50 units long. Now he wants to return sticks to the original state, but he forgot how many sticks he had originally and how long they were originally. Please help him and design a program which computes the smallest possible original length of those sticks. All lengths expressed in units are integers greater than zero.? ?OutputThe output should contains the smallest possible length of original sticks, one per line.?
http://hi.baidu.com/zldiablo/blog/item/df04bcd95e6774ec38012f22.html
http://www.cppblog.com/rakerichard/archive/2010/01/14/105685.html
1、設所有木棍的長度和是sum,那么原長度(也就是輸出)一定能被sum整除,不然就沒法拼了。
2、原來的長度一定大于等于所有木棍中最長的那個
??? 因此可以從最長的長度開始,枚舉每個能被sum整除的長度,因為要求最小的長度,所以搜到第一個就是結果了。
??? 遍歷的過程就是設定一個bool的數組保存每個木棍是不是被用到過,然后用深度優先搜索,判斷每個木棍選或者不選看能不能得到結果。或者說是使用給定的木棍,能不能拼出sum/L個長度是L的木棍。而搜索過程也就是一個一個的去拼長度是L的木棍。
#include <iostream> #include <cstring> #include <algorithm> #include <functional> #include <stdio.h>using namespace std;const int N=64; int stick[N]; bool used[N]; int num;bool DFS(int unused,int rest,int tgtLen)//要使得組合成stNum組,每個組之和為tgtLen;rest表示第i個組還差rest長度就等于tgtLen {if(unused ==0 && rest ==0)return true;if(rest ==0)//上一組已經湊夠tgtLen,這一組要重新湊tgtLenrest = tgtLen;for (int i = 0;i<num;++i){if(used[i])continue;if(stick[i]>rest)continue;used[i] = true;if(DFS(unused - 1,rest - stick[i],tgtLen))return true;used[i] = false;//在這一組還剩余rest的情況下不能滿足條件則,if(stick[i]==rest || rest == tgtLen)//如果在一個組剛開始湊的時候,stick[i]放進去,就導致無解,就說明只要有stick[i]在,就不能有解;break;}return false; }int main() {while (scanf("%d",&num) && num){memset(used,0,sizeof(used));int score =0;for(int i=0;i<num;++i){scanf("%d",stick+i);score +=stick[i];}sort(stick,stick+num,greater<int>());for (int stNum = num;stNum>=1;--stNum){if(score %stNum ==0 && (score/stNum)>=stick[0])if(DFS(num,score/stNum,score/stNum))cout<<score/stNum<<endl;}}return 0; }
總結
- 上一篇: 回溯法---子集和
- 下一篇: Effective STL 条款30