UVA_10664_Luggage(水题)

Peter and his friends are on holiday, so they have decided to make a trip by car to know the north of
Spain. They are seven people and they think that two cars are enough for their luggage.
It’s time to leave . . . and a heap of suitcases are awaiting out of the cars. The drivers disagree
about which suitcase must be put into each boot, because nobody wants one boot to carry more weight
than the other one. Is it possible that the two boots load with the same weight? (Obviously without
unpacking the suitcases!)
Consider m sets of numbers representing suitcases weights, you must decide for each one, if it is
possible to distribute the suitcases into the boots, and the two boots weigh the same.
Input
The first line of the input contains an integer, m, indicating the number of test cases.
For each test case, there is a line containing n integers (1 ≤ n ≤ 20) separated by single spaces.
These integers are the weights of each suitcase. The total sum of the weights of all the suitcases is less
or equal to 200 kilograms.
Output
The output consists of m lines. The i-th line corresponds with the i-th set of suitcases weight and
contains the string ‘YES’ or ‘NO’, depending on the possibility that the two boots load with the same
weight for the respective test case.
Sample Input
3
1 2 1 2 1
2 3 4 1 2 5 10 50 3 50
3 5 2 7 1 7 5 2 8 9 1 25 15 8 3 1 38 45 8 1
Sample Output
NO
YES
YES

题意:给你一组数,问你能否把这组数分成和相等的两部分

思路:把数组排序,然后从大到小往两组中加,哪组少加哪个,加完后如果两组相等就可以做到,否则就不能做到。(注意:输入的时候没有规定每组数的个数,自认为本文的输入方式比较简单)

AC代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
using namespace std;
int a[10010];
int main()
{
    
    
    int n;
    char ch;
    cin>>n;
    while(n--)
    {
    
    
        int tot=0;
        while (~scanf("%d%c",&a[tot],&ch)&&ch==' ')
            tot++;
            sort(a,a+tot+1);
            int l=0,r=0;
        for(int i=tot;i>=0;i--) 
        {
    
    
            if(l<=r)
                {
    
    
                    l+=a[i];
                    continue;
                }

            if(l>r)
                r+=a[i];
        }

        if(l==r)
            printf("YES\n");
            else
                printf("NO\n");

    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43244265/article/details/104414266