题目:
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.
9 5 2 1 5 2 1 5 2 1 4 1 2 3 4 0
6 5
题意:给你一串数字,将他们中的有些数字相加,得到另一串数字他们的值全为k,求这个k的最小值。
思路:显然k的范围是这串数字的最大值到这串数字的总和,然后对这个值进行判断,看这串数字能不能通过变换使其全为k。这里用到搜索。这题搜索的时候需要用剪枝的地方特别多,不然很容易超时,具体见代码。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 1000000000;
const int maxn = 100;
int a[66],vis[66];
int T,n,m;
int sum,len,flag,tot,can;
bool cmp(int a,int b)
{
return a>b;
}
void dfs(int res,int step,int pos)//res:要凑齐tot还需要的数量.setp:搜索过的木棍总数.pos:当前搜索到的位置
{
if(flag)//标记成功与否
return;
if(step==n)
{
flag=1;
return;
}
if(res==0&&step<n)
dfs(tot,step,0);
for(int i=pos;i<n;i++)
{
if(!vis[i]&&!flag&&a[i]<=res)
{
vis[i]=1;
dfs(res-a[i],step+1,i+1);
vis[i]=0;
if(res==tot)//第1次剪枝:如果剩下的res还有tot这么长说明最大的木棍也就是当前这根不能用,直接停止搜索
return;
while(a[i]==a[i+1])//第2次剪枝:如果下一次搜到的和这一次一样,则直接跳过.
i++;
}
}
}
int main()
{
while(scanf("%d",&n)!=EOF&&n)
{
sum=0;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
sort(a,a+n,cmp);
for(int i=a[0];i<=sum;i++)
{
if(sum%i)
continue;
memset(vis,0,sizeof(vis));
flag=0;
tot=i;
dfs(tot,0,0);
if(flag)
{
printf("%d\n",i);
break;
}
}
}
return 0;
}
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 1000000000;
const int maxn = 100;
int a[66],vis[66];
int T,n,m;
int sum,len,flag,tot,can;
bool cmp(int a,int b)
{
return a>b;
}
void dfs(int res,int step,int pos)//res:要凑齐tot还需要的数量.setp:搜索过的木棍总数.pos:当前搜索到的位置
{
if(flag)//标记成功与否
return;
if(step==n)
{
flag=1;
return;
}
if(res==0&&step<n)
dfs(tot,step,0);
for(int i=pos;i<n;i++)
{
if(!vis[i]&&!flag&&a[i]<=res)
{
vis[i]=1;
dfs(res-a[i],step+1,i+1);
vis[i]=0;
if(res==tot)//第1次剪枝:如果剩下的res还有tot这么长说明最大的木棍也就是当前这根不能用,直接停止搜索
return;
while(a[i]==a[i+1])//第2次剪枝:如果下一次搜到的和这一次一样,则直接跳过.
i++;
}
}
}
int main()
{
while(scanf("%d",&n)!=EOF&&n)
{
sum=0;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
sort(a,a+n,cmp);
for(int i=a[0];i<=sum;i++)
{
if(sum%i)
continue;
memset(vis,0,sizeof(vis));
flag=0;
tot=i;
dfs(tot,0,0);
if(flag)
{
printf("%d\n",i);
break;
}
}
}
return 0;
}