题解:CF2148F Gravity Falls

· · 题解

我的第一篇题解~

题意解释

有 n 个不同长度的数组,按左边对齐叠放。\ 如果上面的数组比下面长,多出来的部分就会落下来。\ 可以想象每个数字是一块积木,被重力影响从上面往下掉。\ 我们的目标是让落到最底下的那些数字的字典序最小。

思路

首先,很显然的是,答案很有可能来自不同的数组。\ 并且因为是靠左对齐的,不可能出现答案里一堆来自 x 数组的数字中掺了一个 y 数组的。\ 所以就相当于答案是一段一段的。\ 那么我们就要让每一段的字典序最小,这样整个的字典序就最小。\ 大概思路就是这样 >~<

复杂度

a 数组用 vector 存的,不会炸空间。\ 时间复杂度我也不清楚。\ 实践出真知\ 我有一个通过一直排序实现的代码,大体差不多但会超时。\ 展示一下:

#include <bits/stdc++.h>
using namespace std;
int t,n,k,x,ans[200005],cnt;
vector<int> a[200005];
bool cmp(vector<int> u,vector<int> v){
    for (int i=cnt-1; i<min(u.size(),v.size()); i++){
        if (u[i]<v[i]) return 1;
        if (u[i]>v[i]) return 0;
    }
    if (u.size()<v.size()) return 1;
    return 0;
}
signed main(){
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> t;
    while (t--){
        cin >> n;
        for (int i=1; i<=n; i++){
            cin >> k;
            a[i].clear();
            for (int j=1; j<=k; j++){
                cin >> x;
                a[i].push_back(x);
            }
        }
        cnt=1;
        for (int i=1; i<=n; i++){
            if (a[i].size()<cnt) continue;
            sort(a+i,a+n+1,cmp);
            while (cnt<=a[i].size()){
                ans[cnt] = a[i][cnt-1];
                cnt++;
            }
        }
        for (int i=1; i<cnt; i++) cout << ans[i] << " ";
        cout << "\n";
    }
    return 0;
}

AC Code

代码解释放在注释里面了,\ 大家凑合看吧^~^

#include <bits/stdc++.h>
using namespace std;
#define int long long //可有可无 
/*
变量解释:
ans[] 答案数组(存起来只是方便调试代码,可有可无) 
mx 最长的长度,因为有重力所以也同时是答案的长度
cnt 记录到哪一位了
v[] 打标记 不能重复用同一个
p 看即将要用的是哪一个 
*/ 
int t,n,k,x,ans[200005],mx,cnt,v[200005],p;
vector<int> a[200005];
/*
函数作用:
比较两个vector的字典序,如果都一样就优先更短的 
*/
bool cmp(int l,int r){
    for (int i=cnt; i<min(a[l].size(),a[r].size()); i++){
        if (a[l][i]>a[r][i]) return false;
        if (a[l][i]<a[r][i]) return true;
    }
    return a[l].size()<a[r].size();
}
signed main(){
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> t;
    while (t--){
        cin >> n; 
        //初始化 
        mx=cnt=0;
        memset(v,0,sizeof(v));
        for (int i=1; i<=n; i++){
            cin >> k;
            mx = max(mx,k);
            a[i].clear(); //初始化 
            for (int j=1; j<=k; j++){
                cin >> x;
                a[i].push_back(x);
            }
        }
        //每一位是什么数字 
        while (cnt<mx){
            p=0; //初始化 
            //一个一个看 
            for (int i=1; i<=n; i++){ 
                if (v[i]||a[i].size()<=cnt) continue; //已经用过了或者太短无法下落就跳过 
                if (p==0||cmp(i,p)) p=i; //寻找下一段答案(用字典序最小的) 
            }  
            v[p]=1; //标记上
            for (int i=cnt; i<a[p].size(); i++) ans[i+1]=a[p][i]; //记答案(新下落的部分) 
            cnt = a[p].size(); //更新位置 
        }
        for (int i=1; i<=mx; i++) cout << ans[i] << " ";
        cout << "\n";
    }
    return 0;
}

多测一定记得初始化!!!

感谢观看!~