當(dāng)前位置:
首頁 >
搜索--子集和
發(fā)布時(shí)間:2024/9/30
35
豆豆
一個(gè)整數(shù)數(shù)組,長(zhǎng)度為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,搜索+強(qiáng)剪枝
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、設(shè)所有木棍的長(zhǎng)度和是sum,那么原長(zhǎng)度(也就是輸出)一定能被sum整除,不然就沒法拼了。
2、原來的長(zhǎng)度一定大于等于所有木棍中最長(zhǎng)的那個(gè)
??? 因此可以從最長(zhǎng)的長(zhǎng)度開始,枚舉每個(gè)能被sum整除的長(zhǎng)度,因?yàn)橐笞钚〉拈L(zhǎng)度,所以搜到第一個(gè)就是結(jié)果了。
??? 遍歷的過程就是設(shè)定一個(gè)bool的數(shù)組保存每個(gè)木棍是不是被用到過,然后用深度優(yōu)先搜索,判斷每個(gè)木棍選或者不選看能不能得到結(jié)果?;蛘哒f是使用給定的木棍,能不能拼出sum/L個(gè)長(zhǎng)度是L的木棍。而搜索過程也就是一個(gè)一個(gè)的去拼長(zhǎng)度是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組,每個(gè)組之和為tgtLen;rest表示第i個(gè)組還差rest長(zhǎng)度就等于tgtLen {if(unused ==0 && rest ==0)return true;if(rest ==0)//上一組已經(jīng)湊夠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)//如果在一個(gè)組剛開始湊的時(shí)候,stick[i]放進(jìn)去,就導(dǎo)致無解,就說明只要有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; }
總結(jié)
- 上一篇: 回溯法---子集和
- 下一篇: Effective STL 条款30