11059 - Maximum Product (UVA)

题目链接如下:

Online Judge

简单的暴力如下:

#include 
#include 
// #define debug

int n, t, kase = 0;
std::vector vec;

long long process(){
    long long maxx = 0;
    for (int i = 0; i < vec.size(); ++i){
        long long temp = 1;
        for (int j = i; j < vec.size(); ++j){
            temp *= vec[j];
            if (temp > maxx){
                maxx = temp;
            }
        }
    }
    return maxx;
}

int main(){
    #ifdef debug
    freopen("0.txt", "r", stdin);
    freopen("1.txt", "w", stdout);
    #endif
    while (scanf("%d", &n) != EOF){
        vec.clear();
        while (n--){
            scanf("%d", &t);
            vec.push_back(t);
        }
        printf("Case #%d: The maximum product is %lld.\n\n", ++kase, process());
    }
    #ifdef debug
    fclose(stdin);
    fclose(stdout);
    #endif
    return 0;
}

然后看到一个比较厉害的dp解法 UVa 11059 - Maximum Product_uva-11059]-CSDN博客

于是改写了我的代码如下:

#include 
#include 
// #define debug

int n, t, kase = 0;
std::vector vec;

long long process(){
    long long maxx = 0;
    long long pos = 0;
    long long neg = 0;
    for (int i = 0; i < vec.size(); ++i){
        if (!vec[i]){
            pos = neg = 0;
        } else if (vec[i] > 0){
            pos = pos * vec[i];
            neg = neg * vec[i];
            if (!pos){
                pos = vec[i];
            }
        } else if (vec[i] < 0){
            long long temp = pos;
            pos = neg * vec[i];
            neg = temp * vec[i];
            if (!neg){
                neg = vec[i];
            }
        }
        maxx = std::max(maxx, pos);
    }
    return maxx;
}

int main(){
    #ifdef debug
    freopen("0.txt", "r", stdin);
    freopen("1.txt", "w", stdout);
    #endif
    while (scanf("%d", &n) != EOF){
        vec.clear();
        while (n--){
            scanf("%d", &t);
            vec.push_back(t);
        }
        printf("Case #%d: The maximum product is %lld.\n\n", ++kase, process());
    }
    #ifdef debug
    fclose(stdin);
    fclose(stdout);
    #endif
    return 0;
}

你可能感兴趣的:(UVA,算法)