OJ-1020 I think it

本文介绍了一个通过编程解决的问题:对于一组给定的整数,找出所有可能的子集和中第二大的数值。该问题通过多次遍历并排序输入的整数来找到最大的子集和,再通过额外的遍历来确定次大的子集和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

Xiao Ming is only seven years old, Now I give him some numbers, and ask him what is the second largest sum if he can choose a part of them. For example, if I give him 1 、 2 、 3 , then he should tell me 5 as 6 is the largest and 5 is the second. I think it is too hard for him, isn ’ t it?

Input

Standard input will contain multiple test cases. The first line of the input is a single integer T (1 <= T <=10) which is the number of test cases. And it will be followed by T consecutive test cases.
Each test case starts with a line containing an integer N (1<N<10) , the number I give Xiao Ming . The second line contains N Integer numbers ai (-10<ai<10),

Output

For each test case, output the answer.

Sample Input

2
3
1 2 3
4
0 1 2 3

Sample Output

5
5

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int m,n,i,j,k;
    int sum,sum1,sum2;
    int a[100];
    cin>>m;
    while(m--)
    {
        cin>>n;
        for(i=0;i<n;i++)
        {
            cin>>a[i];
        }
        sort(a,a+n);
        sum=a[0];sum1=0;sum2=a[0];
        for(i=0;i<n;i++)
        {
            for(j=i;j<n;j++)
            {
                sum1=0;
                for(k=i;k<=j;k++)
                {
                    sum1+=a[k];
                }
                if(sum1>sum)
                    sum=sum1;
            }
        }
        for(i=0;i<n;i++)
        {
            for(j=i;j<n;j++)
            {
                sum1=0;
                for(k=i;k<=j;k++)
                {
                    sum1+=a[k];
                }
                if(sum1>sum2&&sum1<sum)
                    sum2=sum1;
            }
        }
        cout<<sum2<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值