题解 P7390

· · 题解

好怀念那段时光啊。

但现在也不错不是嘛。

思路

一个事实:如果每个点度数 \in[1,n) 且所有点度数和 =2n-2,那么可以连出树。

证明:每次选择度数最小的点和度数最大的点连边。

  1. 度数最小的点一定是 1。
  2. 度数为 n-1 的点在 n>2 的时候不能存在 2 个。
  3. 度数最大值在 n>2 时一定 >1。

另一个事实:如果一张图上最大值和次大值之间能连边但没有连边,存在更优的调整。

证明:假设 A,B 是最大值,C 是生成树上和 A 相邻,但不在 (A,B) 路径上的边,D 是树上 B 的父亲,我们的一个简单调整方法是将 (A,C),(B,D) 变为 (A,B),(C,D)。

所以事实上我们每次做的就是选一个权值最大的非叶子节点,再在剩下的点里取权值最大的连边。

时间复杂度直接看起来要带 \log,但稍加分析会发现并不存在:对于度数 \geq 2 的点,在进行一次缩点之后,连通块一定是一个前缀和若干散点,所以精细实现一下就好。

代码

#include<bits/stdc++.h>
#define ll long long
using namespace std;
inline int read(){
   int s=0,w=1;
   char ch=getchar();
   while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
   while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
   return s*w;
}
const int N=5e5;
int a[10000003],b[10000003];
int c1[500003];
vector<int> c2[500003];
deque<pair<int,int>> q1,q2,q3,q4;
unsigned seed;
unsigned rnd(unsigned x){
    x^=x<<13;
    x^=x>>17;
    x^=x<<5;
    return x;
}
int rad(int x,int y){
    seed=rnd(seed);
    return seed%(y-x+1)+x;
}
signed main()
{
    int n;
    if(!read())
    {
        n=read(); 
        for(int i=1; i<=n; ++i) a[i]=read();
        for(int i=1; i<=n; ++i) b[i]=read();
    }
    else
    {
        n=read(); 
        scanf("%u",&seed);
        for(int i=1; i<=n; i++)
            a[i]=1,b[i]=rad(1,N);
        for(int i=1; i<=n-2; ++i)
            ++a[rad(1,n)];
    }
    for(int i=1; i<=n; ++i)
        if(a[i]==1) ++c1[b[i]];
        else c2[b[i]].push_back(a[i]);
    for(int i=N; i>=1; --i) if(c1[i])
        q1.push_back({i,c1[i]});
    for(int i=N; i>=1; --i)
        for(int j:c2[i])
            q2.push_back({i,j});
    ll ans=0;
    while(!q3.empty()||!q2.empty())
    {
        if(q3.empty())
            q3.push_back(q2.front()),q2.pop_front();
        auto [x,y]=q3.front();
        q3.pop_front();
        int last=q3.empty();
        for(int i=1; i<=y-last; ++i,last=q3.empty())
        {
            int mx=-1;
            if(!q1.empty()&&q1.front().first>mx)
                mx=q1.front().first;
            if(!q2.empty()&&q2.front().first>mx)
                mx=q2.front().first;
            if(!q4.empty()&&q4.front().first>mx)
                mx=q4.front().first;
            ans+=1ll*mx*x;
            if(!q1.empty()&&q1.front().first==mx)
                {if(!--q1[0].second) q1.pop_front();}
            else if(!q2.empty()&&q2.front().first==mx)
                q3.push_back({q2.front().first,
                q2.front().second-1}),q2.pop_front();
            else if(!q4.empty()&&q4.front().first==mx)
                q4.pop_front();
            else puts("HaitangSuki");
        }
        if(last) q4.push_back({x,1});
    }
    vector<int> V;
    for(auto [x,y]:q1)
        for(int i=1; i<=y; ++i)
            V.push_back(x);
    for(auto [x,y]:q4)
        for(int i=1; i<=y; ++i)
            V.push_back(x);
    printf("%lld\n",ans+1ll*V[0]*V[1]);
    return 0;
}