pku+acm+1011

搜索类的题目,参考自:http://hi.baidu.com/alpc29_33/blog/item/43205f10c41dc377ca80c488.html

纠结了N天的一道题。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <functional>
using namespace std;

int parts[65];
int used[65];
int num_parts,// <= 64
	origin_stick_len,origin_stick_count;

int dfs(int num,int len,int next)
{
	if(num == 0)return 1;
	
	if(len == 0)
	{  
		int i;
		for(i = 0;i < num_parts;i++)		
			if(used[i] == 0)
				break;

		if(i == num_parts)
		{
			if(num - 1 == 0)return 1;
			else return 0;
		}
		

		used[i] = 1;
		if(dfs(num-1,origin_stick_len - parts[i],i+1))
			return 1;
		else
		{
			used[i]=0;
			return 0;
		}
	}
	else
	{
		for(int i = next; i < num_parts; i++)
		{
			if(used[i] == 0 && parts[i] <= len)
			{
				used[i] = 1;
				
				if(dfs(num,len-parts[i],i+1))
					return 1;
				else
				{
					used[i] = 0;     
					while(i+1 < num_parts && parts[i+1] == parts[i])
						++i;					
				}
			}
		}
		return 0;
	}
}

int main()
{
	freopen("in.txt","rt",stdin);
	while(cin>>num_parts && num_parts != 0)
	{
		int i,sum=0;
		for(i=0;i<num_parts;i++)
		{
			cin>>parts[i];
			sum += parts[i];			
		}
		sort(parts,parts+num_parts,greater<int>());

		for(i = parts[0]; /*i<=sum/2*/; i++)
		{
			if(sum%i==0)
			{
				origin_stick_len = i;
				origin_stick_count = sum/i;
				memset(used, 0, sizeof(used));

				int ans = dfs(origin_stick_count,origin_stick_len,0);    
				if(ans == 1)
				{
					cout<<i<<endl;
					break;
				}
			}
		}
	}
	return 0;
}

测试数据:

9
5 2 1 5 2 1 5 2 1

9
15 3 2 11 4 1 8 8 8

6
6 2 2 4 8 8

5
1 1 1 1 1

2
1 1

4
2 2 9 9

3
1 2 3

64
40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40
40 40 43 42 42 41 10 4 40 40 40 40 40 40 40 40 40 40 40 40 40
40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40
40

7
49 48 47 46 45 44 43

7
3 4 5 5 5 5 13

7
2 7 7 7 7 10 20

6
1 2 3 11 11 20

7
63 2 44 12 60 35 60

9
5 2 1 5 2 1 5 2 1

4
1 2 3 4

64
32 32 32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32 32 32
32 32 32 32 32 32 32 32 32 32
33 33 31 31

64
40 40 30 35 35 26 15 40 40 40 40 40 40 40 40 40 40 40 40 40 40
40 40 43 42 42 41 10 4 40 40 40 40 40 40 40 40 40 40 40 40 40
40 25 39 46 40 10 4 40 40 37 18 17 16 15 40 40 40 40 40 40 40
40

45
15 3 2 11 4 1 8 8 8 15 3 2 11 4 1 8 8 8 15 3 2 11 4 1 8 8 8 15 3 2 11 4 1 8 8 8
15 3 2 11 4 1 8 8 8

0

结果:
20
10
1
1
11
3
1251
322
20
30
24
276
6
5
64
454
20

阅读更多
文章标签: 测试 2010 c
个人分类: POJ ACM
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭