201301 JAVA题目0-1级 华为OJ

编写一个函数,传入一个int型数组,返回该数组能否分成两组,使得两组中各元素加起来的和相等,并且,所有5的倍数必须在其中一个组中,所有3的倍数在另一个组中(不包括5的倍数),能满足以上条件,返回true;不满足时返回false

大致原理 输入的数组是a[] 5的倍数放在a5[]  3的倍数放在a3[]  然后如果a[]除去a3[] a5[]中剩余的元素中

存在部分和等于a[]/2- a[]5 就正确时true的  因为不妨设等于a[]/2- a[]5 的这一部分元素为a1[]   另一部分为a[]2

既有 a[]1+a[]2+a3[]+a5[] = a[] 如果存在a1[] +a[]5  = a[]/2  必然存在 a[]2+a[]3 = a[]/2

所以主要求a[]除去a3[] a5[]中剩余的元素的全排列 用next_permutation函数


///数组分为两个加起来相同的数组//
#include  <iostream>
#include <algorithm> 
using namespace  std;
int main()
{
		int a[100] = { 0 };
		int a5[100] = { 0 };
		int a3[100] = { 0 }, count5 = 0, count3 = 0;
	int n;
	cin >> n;
	bool Flag = false;
	int total = 0;
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
		total += a[i];
	}
	if (total % 2 != 0)
	{
		Flag = false;
	}
	int sum3 = 0;
	int sum5 = 0;
	for (int i = 0; i < n; i++)
	{
		if (a[i] % 5 == 0 && a[i] != 0)
		{
			a5[count5++] = a[i];
			sum5 += a[i];
			a[i] = 0;
		}
	}
	for (int i = 0; i < n; i++)
	{
		if (a[i] % 3 == 0 && a[i] != 0)
		{
			a3[count3++] = a[i];
			sum3 += a[i];
			a[i] = 0;
			
		}
	}
	int temp1 = total / 2 - sum5;
	int temp2 = total / 2 - sum3;
	int temp = 0;
	do
	{
		for (int i = 0; i < n; i++)
		{
			temp += a[i];
			if (temp == temp1)
			{
				Flag = true;
				break;
			}
		}
	}
    while(	next_permutation(a, a + n)); 
	if (Flag == true)
	{
		cout << "true" << endl;
	}
	else if (Flag == false)
	{
		cout << "false" << endl;
	}
	return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值