zoukankan      html  css  js  c++  java
  • HackerRank

    It is modulo version of "max sum of contiguous subarray". So similar pattern can be applied too, but with tricks regarding to modulo ops.

    I checked editorials, and found that, the quickcorrect solution requires sharp insight into internal characteristics and mechanism of one problem... which I'm still lack with...

    Modulo, you should feel of it is as a roll-over game. If within the scope, like (3 - 1)%3, there's nothing special; and if beyond the scope like (1 - 3)%3, you get it roll-over from the beginning..

    And another key trick is, std::lower_bound() upon std::set is slower than set::lower_bound()..

    #include <cmath>
    #include <cstdio>
    #include <vector>
    #include <map>
    #include <set>
    #include <unordered_set>
    #include <string>
    #include <climits>
    #include <iostream>
    #include <algorithm>
    #include <unordered_map>
    #include <unordered_set>
    using namespace std;
    
    int dp(vector<int> &in, int m)
    {
        int ret = 0;
        size_t len = in.size();
    
        vector<int> dp(len, 0);
    
        for (int ilen = 1; ilen <= len; ilen ++)
        for (int i = 0; i <= len - ilen; i++)
        {
            dp[i] += in[i + ilen - 1];
            ret = std::max(ret, dp[i] % m);
        }
        return ret;
    }
    
    int main()
    {
        int t; cin >> t;
        while (t--)
        {
            long long n, m; cin >> n >> m;
        
            long long x, prefix = 0, ret = 0;
            set<long long> s;
            s.insert(0);
            for (int i = 0; i < n; i++)
            {
                cin >> x;
                prefix = (prefix + x) % m;
                
                //    Case 1: prefix - 0 
                //        (for smaller prefixes)
                ret = std::max(ret, prefix); 
    
                //    Case 2: prefix - smallest_larer + m 
                //        (for larger prefixes)
                auto it = s.lower_bound(prefix + 1);
                if (it != s.end())
                {
                    ret = std::max(ret, prefix - *it + m);
                }
    
                s.insert(prefix);
            }
            cout << ret << endl;
        }
        return 0;
    }
  • 相关阅读:
    判断输入的是否是汉字(中文,不包括中文符号)
    第XX行将截断字符串或二进制数据。语句已终止
    Joomla学习之旅开始啦
    bean加载与注入之重新理解 L
    Excelsior JET 7.6 MP5 发布
    Squid Analyzer 5.1 发布,Squid日志统计
    flashrd 1.3 发布,OpenBSD 安装器
    Oracle 宣布 MySQL 5.6 正式版发布
    Spring Hateoas 0.4 发布
    MacPorts 2.1.3 发布,Mac 软件包管理
  • 原文地址:https://www.cnblogs.com/tonix/p/4522240.html
Copyright © 2011-2022 走看看