c++ - Spoj- 数组的最大子集

标签 c++ algorithm

我正在解决这个 spoj 问题。 http://www.spoj.com/problems/MAXSUB/ 我所有的测试用例都正常工作,但我在 spoj 中得到了错误的答案。 我试图改变我的代码很多但仍然得到了 WA。 当我添加总和以防止溢出时,我正在使用 mod。我应该这样做吗?

> my algorithm:
> sum of all +ve num will be the maximum sum.
> if there is no +ve number after sorting take the last element as the max number.
> case 1: last element is -ve.
>       number of subsets=number of times it occurs
> case 2: last element is 0.
>      cnt=number of 0's.
>      number of subsets=2^cnt-1(excluding the null set)

有人可以帮忙吗??

#include<iostream>
#include<cstdio>
#include<deque>
#include<algorithm>
#include<math.h>

#define MOD 1000000009


using namespace std;
typedef long long int L;
int main(){
int t;
L n;
scanf("%d",&t);
while(t--){
    scanf("%lld",&n);
    L arr[51000],sum=0LL;
    L cnt=1LL;

    for(int i=0;i<n;i++){
        scanf("%lld",&arr[i]); 
        if(arr[i]>0){
            sum+=(long long)arr[i];
            sum%=MOD;
         //   f=1;
        }
    }
        sort(arr,arr+n);
        if(sum==0){//this is to check if there is no +ve num
            sum=arr[n-1];
            for(int j=n-2;j>=0;j--){
                if(sum==arr[j])
                  cnt++;
                 else
                  break;
             }
             if(sum==0){//this is to check if the maximum num is 0
                 L num=1;
                for(int k=0;k<cnt;k++){
                    num=(L)(num*2)%MOD;//if sum==0 then num of subset is 2^cnt-1
                }//decrementing 1 from 2^cnt coz we do not include null set
                cnt=num-1;
              }
          }
          cnt=cnt%MOD;
    printf("%lld %lld\n",sum,cnt);
}

最佳答案

我没有逐行阅读你的代码,但我认为你至少漏掉了一个案例 -

输入中既可以有正数也可以有零,在这种情况下答案应该是2^(# of zeros)

关于c++ - Spoj- 数组的最大子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18425270/

相关文章:

c++ - 用Qt通过参数调用另一个应用程序

javascript - 有人可以用外行的术语解释这个功能是如何工作的吗?

c++ - 在 linux 下的 GCC 中使用 std::thread 的正确链接选项是什么?

c++ - 如何使用 ifstream 和 istreambuf_iterator 将二进制文件读取为 float?

c++ - 为了在 C++ 中线程安全,我应该使用互斥锁保护原始类型上的操作吗?

java - 生成特定的数字序列

algorithm - 计数排序的性能

c# - 如何在 C# 中生成具有各种大小的单元格的随机洪水填充

algorithm - 为什么 LRU 优于 FIFO?

c++ - 将参数传递给 "array-like"容器构造函数