codeforces(E. Minimum Array)set应用

在这里插入图片描述

题意很简单,按照贪心去找就行,比如a=3,n=5,首先找x=(n-a)=2,没有2就找3,以此类推,超出了n则从0开始往后找,每个元素都是如此

如果按照这样找的话复杂度是O(n2),肯定会T,因此用set,但b数组中有重复元素,因此可以用std::multiset,可以允许有重复元素,并且可以在O(logn)的时间内实现插入、删除,再配合二分lower_bound在O(logn)的时间内查找。

代码:

#include <bits/stdc++.h>
#define ll long long
using namespace std;

int a[200005];
int d[200005];
int c[200005];
multiset<int>b;
multiset<int>::iterator it;
multiset<int>::iterator ic;
int main()
{
    
    
    int n,x;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
    
    
        scanf("%d",&a[i]);
        d[i]=n-a[i];
    }
    for(int i=1;i<=n;i++)
    {
    
    
        scanf("%d",&x);
        b.insert(x);
    }
    for(int i=1;i<=n;i++)
    {
    
    
        x=d[i];
        ic=b.end();ic--;
        it=b.lower_bound(x);
        if(*ic>=x)
        {
    
    
            c[i]=(a[i]+*it)%n;
            b.erase(it);
        }
        else
        {
    
    
            it=b.lower_bound(0);
            c[i]=(a[i]+*it)%n;
            b.erase(it);
        }
    }
    for(int i=1;i<=n;i++)
    {
    
    
        printf("%d ",c[i]);
    }
    printf("\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43781431/article/details/105742549