当前位置: 代码迷 >> 综合 >> Sticks//拼火柴//Central Europe 1995//dfs
  详细解决方案

Sticks//拼火柴//Central Europe 1995//dfs

热度:79   发布时间:2024-01-10 06:56:26.0

Sticks//拼火柴//POJ - 1011//dfs


题目

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.
Input
The input contains blocks of 2 lines. The first line contains the number of sticks parts after cutting, there are at most 64 sticks. The second line contains the lengths of those parts separated by the space. The last line of the file contains zero.
Output
The output should contains the smallest possible length of original sticks, one per line.
Sample Input
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
Sample Output
6
5
大意
某脑残把等长火柴棍砍断让你还原,求原等长火柴的长度。
网页链接:https://vjudge.net/contest/347799#problem/E(Central Europe 1995)

思路

答案一定是总长的因子,从小到大遍历其因子,其对应的另一个因子是分成的组数,不超过题目给定的段数,有合适的因子就是最小合适的。对于每一个因子,通过贪心+回溯来组合出适合的数。组数达到目标作为判断是否可行的标准,不可行则回溯。

代码

#include <iostream>//以组数收齐为判断标准即可
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;int n,t[100],vis[100];//vis用于判断是否用过,0没用过
bool judge;
int sum;
void dfs(int len,int sumn,int gpn,int gpa,int temp)
{
    if(gpn==gpa)//所有的组都收集齐了{
    judge=true;return;}if(sumn==len) //收集齐了一组{
    dfs(len,0,gpn+1,gpa,0);}for(int i=temp;i<n&&!judge;i++)//有一条线成功后就不需要继续{
    if(!vis[i]&&t[i]+sumn<=len){
    vis[i]=1;dfs(len,sumn+t[i],gpn,gpa,i);if(judge) return;vis[i]=0;if(sumn==0||sumn+t[i]==len) return ;//剪枝}}
}
bool judgen(int len,int gp)
{
    memset(vis,0,sizeof vis);judge=false;dfs(len,0,0,gp,0);return judge;
}
bool cmp(int a,int b)
{
    return a>b;
}
int main()
{
    while(1){
    cin>>n;if(n==0) break;sum=0;for(int i=0;i<n;i++) {
    cin>>t[i];sum+=t[i];}sort(t,t+n,cmp);int ans=sum;for(int i=n;i>1;i--)if(sum%i==0&&t[n-1]<=sum/i&&judgen(sum/i,i))//从小往大{
    ans=sum/i;break;}cout<<ans<<endl;}return 0;
}

注意

如果没有回溯会导致一些情况没有考虑完全
纯贪心特殊数据:
9
15 11 8 8 8 4 3 2 1
长度×组数即为总长
有符合的情况直接跳过剩余的任何情况

  相关解决方案