HDU 1455 POJ 1011 Sticks 搜索

http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=20608

                        **

                        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 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 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
這個題搜索加減枝,這個去年做過的題目,現在做起來還是手殘了,敲挺久的,就在分支的計算上失誤了。。。手殘黨。。。。不該!

#include<bits/stdc++.h>
using namespace std;
const int N = 70;
#define fi(i,n) for(int i = 0; i < n; i ++)
#define fin(i,n1,n2) for(int i = n1; i < n2; i ++)
int n, stick_sum, sum, sticks[N];
bool vis[N];
bool cmp(int a, int b) {return a > b;}

bool dfs(int cnt, int st, int len)
{
    if(cnt == n) return 1;
    int sample = -1;
    fin(i,st,n) if(!vis[i] && sticks[i] != sample)
    {
        vis[i] = 1;
        if(sticks[i] + len < stick_sum)
        {
            if(dfs(cnt + 1, i + 1, len + sticks[i])) return 1;
            else sample = sticks[i];
        }
        else if(sticks[i] + len == stick_sum)
        {
            if(dfs(cnt + 1, 0, 0)) return 1;
            else sample = sticks[i];
        }
        vis[i] = 0;
        if(!len) break;
    }
    return 0;
}

int main()
{
    while(~scanf("%d", &n), n)
    {
        sum = 0;
        memset(vis, 0, sizeof(vis));
        fi(i,n) 
        {
            scanf("%d", sticks + i);
            sum += sticks[i];
        }
        sort(sticks, sticks + n, cmp);
        for(stick_sum = sticks[0]; stick_sum <= sum; stick_sum ++)
            if(sum % stick_sum == 0 && dfs(0, 0, 0))
            {
                printf("%d\n", stick_sum);
                break;
            }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章