UVA

来源:互联网 发布:廖雪峰python教程视频 编辑:程序博客网 时间:2024/06/06 01:36

点击打开题目链接

Sticks

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.

Input

The input file contains blocks of 2 lines. The first line contains the number of sticks parts after cutting.
The second line contains the lengths of those parts separated by the space. The last line of the file
contains ‘0’.

Output

The output file 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

题目大意:乔治将很多相等长度的木棒砍成n个小木棒。希望你能拼成原来的样子,并使拼得的每个木棒长度最小。
思路:dfs+剪枝
①所有小木棒和一定能被原来木棒的根数整除并且原来木棒的长度一定≥现在每段小木棒的最大长度。
②木棒从长到短sort,提高dfs效率。
③如果当前木棒不能拼得,则下一个木棒如果与它长度相等,跳过。
④如果找不到某木棒之后得任意木棒可以与它拼得,直接返回false。因为这根木棒最后肯定孤立。

附上AC代码:

#include<iostream>#include<algorithm>#include<cstdio>#include<cstring>using namespace std;const int maxn = 150;int n;int mind, sum;int temp;int a[maxn];int vis[maxn];int dfs(int cnt, int pos, int sum){    if (cnt == n)        return 1;    for (int i = pos; i < n; i++)    {        if (vis[i])continue;        if (sum + a[i] < temp)        {            vis[i] = 1;            if (dfs(cnt + 1, i + 1, sum + a[i]))                return 1;            vis[i] = 0;            while (a[i] == a[i + 1] && i + 1 < n)i++;//剪枝3:如果当前木棒拼不上并且下一个木棒长度和这个长度相等,则跳过        }        else if (sum + a[i] == temp)        {            vis[i] = 1;            if (dfs(cnt + 1, 0, 0))                return 1;            vis[i] = 0;            return 0;//剪枝2:如果当前木棒与后面所有木棒都拼不上;直接返回false;        }        if (sum == 0)            return 0;    }    return 0;}int cmp(int a, int b){    return a > b;}int main(){//  freopen("input","r",stdin);//  freopen("output","w",stdout);    ios::sync_with_stdio(false);    while (cin >> n, n)    {        mind = 0;        sum = 0;        fill(a, a + maxn, 0);        fill(vis, vis + maxn, 0);        for (int i = 0; i < n; i++)        {            cin >> a[i];            sum += a[i];            mind = max(mind, a[i]);        }        sort(a , a + n , cmp);        for (int i = n; i > 0; i--)        {            temp = sum/i;            if (sum % i != 0 || temp < mind)continue;//剪枝1:不能被整除或者单个长度小于mind            else            {                memset(vis, 0, sizeof(vis));                if (dfs(0, 0, 0))                {                    cout << temp << endl;                    break;                }            }        }    }    return 0;}
0 0
原创粉丝点击