zoukankan      html  css  js  c++  java
  • HDU5265——贪心——pog loves szh II

    Problem Description
    Pog and Szh are playing games.There is a sequence with $n$ numbers, Pog will choose a number A from the sequence. Szh will choose an another number named B from the rest in the sequence. Then the score will be $(A+B)$ mod $p$.They hope to get the largest score.And what is the largest score?
     
    Input
    Several groups of data (no more than $5$ groups,$n geq 1000$).

    For each case: 

    The following line contains two integers,$n(2 leq n leq 100000)$,$p(1 leq p leq 2^{31}-1)$。

    The following line contains $n$ integers $a_i(0 leq a_i leq 2^{31}-1)$。
     
    Output
    For each case,output an integer means the largest score.
     
    Sample Input
    4 4 1 2 3 0 4 4 0 0 2 2
     
    Sample Output
    3 2
     
    Source
     
    Recommend
    hujie   |   We have carefully selected several similar problems for you:  5267 5266 5263 5262 5261 
     
    由于序列中的数可能超过P,所以将所有的数读入后进行取模操作。之后将取模后的所有数从小到大排序。题目要求我们求不同位置的两个数的和在取模意义下的最大值,而现在所有数都是小于P且排好序的。因此设我任意选了两个数是XY,显然0X+Y2P2。若X+Y<P,则这次选数的答案就是X+Y,若X+YP,则答案是X+YP。
    那么我们可以这样做:将其中最大的两个数字相加取模,设为一个可能的答案记录在ANS中。这个答案是第二种情况的最大值。再对排序好的序列进行枚举,对每个枚举到的数,找出最大的数,使这个数与枚举到的数相加后的和最大且小于P,将之记为可能的答案并于之前找到的最大值ANS进行比较。这个答案是第一种情况中的可能的最大值。而普通的枚举是要超时的,但是我们发现如果从小到大枚举第一个数,那么另一个匹配的数显然是从大到小的,因此可以用一个NOW记录当前另一个匹配的数的位置,每次枚举时NOW递减至符合条件。可以做到O(n)的时间复杂度。
    综上所述,时间复杂度为快速排序的O(nlogn),空间复杂度为O(n)。注意一些特殊情况如同一个位置不能多次选。
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    long long   a[100100];
    int main()
    {
        
        int n;
        long long p;
        while(~scanf("%d%lld",&n,&p)){
            for(int i = 1; i <= n; i++){
                scanf("%lld",&a[i]);
                a[i]%=p;
            }
            sort(a+1,a+n+1);
            long long  max1 = (a[n]+a[n-1])%p;
            int now = n;
            for(int i = 1; i < now ;i++){
                
                max1 = max(max1,(a[i]+a[now])%p);
                if(a[i]+a[now] >= p){
                    now--;
                    i--;
                }
               }
            printf("%lld
    ",max1);
        }
        return  0;
    }
    

      

     
  • 相关阅读:
    [LeetCode]2. Add Two Numbers链表相加
    Integration between Dynamics 365 and Dynamics 365 Finance and Operation
    向视图列添加自定义图标和提示信息 -- PowerApps / Dynamics365
    Update the Power Apps portals solution
    Migrate portal configuration
    Use variable to setup related components visible
    Loyalty management on Retail of Dynamic 365
    Modern Fluent UI controls in Power Apps
    Change screen size and orientation of a canvas app in Power App
    Communication Plan for Power Platform
  • 原文地址:https://www.cnblogs.com/zero-begin/p/4561764.html
Copyright © 2011-2022 走看看