codeforces1230A水题(DFS)

awid has four bags of candies. The i-th of them contains ai candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total?

Note, that you can’t keep bags for yourself or throw them away, each bag should be given to one of the friends.

Input
The only line contains four integers a1, a2, a3 and a4 (1≤ai≤100) — the numbers of candies in each bag.

Output
Output YES if it’s possible to give the bags to Dawid’s friends so that both friends receive the same amount of candies, or NO otherwise. Each character can be printed in any case (either uppercase or lowercase).

Examples
Input
1 7 11 5
Output
YES
Input
7 3 2 5
Output
NO
Note
In the first sample test, Dawid can give the first and the third bag to the first friend, and the second and the fourth bag to the second friend. This way, each friend will receive 12 candies.

In the second sample test, it’s impossible to distribute the bags.

#include<iostream>
using namespace std;
int a[6],sum;
bool flag;
void dfs(int x,int d) {
        if(x==sum/2) {
            flag=1;
            return ;
    	}
    if(flag==1) {return ; }
    if(d==5) {return ;}
    dfs(x+a[d],d+1);
    dfs(x,d+1);
}
int main(){
    cin>>a[1]>>a[2]>>a[3]>>a[4];
    sum+=a[1]+a[2]+a[3]+a[4];
    if(sum%2!=0) {
        cout<<"NO"<<endl;
    } else {
    	dfs(0,1);
      	if(flag==1) {
            cout<<"YES"<<endl;
        } else {
            cout<<"NO"<<endl;
        }
    }
  return 0;
}

没有什么好说的,这里可以多加一个判断,总和是否为奇数,是就直接输出NO,
看了下别人写的其实也不需要dfs,直接把所有情况列举出来就可以,

using namespace std;
int a[6],sum,temp;
bool flag;
int main(){
    cin>>a[1]>>a[2]>>a[3]>>a[4];
    sum+=a[1]+a[2]+a[3]+a[4];
    if(sum%2!=0) {
        cout<<"NO"<<endl;
    } else {
		if(a[1]+a[2]==sum/2 || a[1]==sum/2 || a[2]==sum/2 || a[3]==sum/2 || a[4]==sum/2 || a[1]+a[3]==sum/2 || a[1]+a[4]==sum/2 || a[2]+a[3]==sum/2 || a[2]+a[4]==sum/2 || a[3]+a[4]==sum/2) {
            cout<<"YES"<<endl;
        } else {
            cout<<"NO"<<endl;
        }
    }
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值