• [Luogu] CF888E Maximum Subsequence


    (Link)

    Description

    给一个长度为(n)的数列和(m),在数列任选若干个数,使得他们的和对(m)取模后最大。
    (n ≤ 35, 1 ≤ m ≤ 10^9)

    Solution

    (n)这么小,一看就知道要爆搜。但纯搜索是(O(2^n))的,跑不过去。这时可以考虑(Meet in the Middle)

    (Meet in Middle)的理解:

    对于一个复杂度是(O(2^n))的搜索算法,我们把他拆成(O((2^{frac{n}{2}})^2))的做法,再想办法用一些诸如贪心之类的线性算法,将(O((2^{frac{n}{2}})^2))的复杂度降低为(O(2 imes2^{frac{n}{2}}))

    对于本题来说也很好理解。我们先暴力枚举前一半的数能凑出的所有和(对(m)取模)。对于后一半,凑出一个和之后,肯定是贪心地选第一次凑出的和中,小于(m-sum)里最大的。具体可以用(lowerunderline{}bound)实现。

    Code

    #include <bits/stdc++.h>
    
    using namespace std;
    
    #define ll long long
    
    int n, m, t, a[40];
    
    ll res, num[300005];
    
    int read()
    {
    	int x = 0, fl = 1; char ch = getchar();
    	while (ch < '0' || ch > '9') { if (ch == '-') fl = -1; ch = getchar();}
    	while (ch >= '0' && ch <= '9') {x = (x << 1) + (x << 3) + ch - '0'; ch = getchar();}
    	return x * fl;
    }
    
    void dfs1(int x, ll sum)
    {
    	if (x == n / 2 + 1)
    	{
    		num[ ++ t] = sum;
    		return;
    	}
    	dfs1(x + 1, (sum + a[x]) % m);
    	dfs1(x + 1, sum);
    	return;
    }
    
    void dfs2(int x, ll sum)
    {
    	if (x == n + 1)
    	{
    		int pos = lower_bound(num + 1, num + t + 1, m - sum) - num;
    		if (pos == t + 1) pos = t;
    		else pos -- ;
    		res = max(res, (sum + num[pos]) % m);
    		return;
    	}
    	dfs2(x + 1, (sum + a[x]) % m);
    	dfs2(x + 1, sum);
    	return;
    }
    
    int main()
    {
    	n = read(); m = read();
    	for (int i = 1; i <= n; i ++ )
    		a[i] = read();
    	dfs1(1, 0ll);
    	sort(num + 1, num + t + 1);
    	dfs2(n / 2 + 1, 0ll);
    	printf("%lld
    ", res);
     	return 0;
    }
    
  • 相关阅读:
    css-box-shadowing
    css- :before :after
    css: line-height 与box-sizing
    金蝶数据库后台追踪
    钉钉审批开发,空白内容
    asp.net c#语言实现钉钉鉴权验证
    钉钉事件回调c#测试完成
    钉钉C#发起审批实例demo
    asp.net c#语言实现钉钉鉴权验证
    图片码
  • 原文地址:https://www.cnblogs.com/andysj/p/13971205.html
Copyright © 2020-2023  润新知