2025牛客寒假算法基础集训营3

K.智乃的逆序数

冒泡排序的交换次数即为逆序对的个数,所以交换即可创造逆序对。由于给定的数组是连续的所以所有数组按第一个数字大小排序即可得到最少的逆序对,接下来创造逆序对即可,若最后无法创造那么输出NO

#include <bits/stdc++.h>

#define lowbit(x) ((x)&(-x))
#define all(x) x.begin(),x.end()
#define int long long
using namespace std;
const int N = 1e3 + 10;
const int MOD = 998244353;

vector<vector<int>> a(N);
vector<int> temp;
map<int, int> mp;

bool comp(vector<int> x, vector<int> y) {
    return x[0] < y[0];
}

void solve() {
    int n, k;
    cin >> n >> k;
    for (int i = 1; i <= n; i++) {
        int m;
        cin >> m;
        for (int j = 1; j <= m; j++) {
            int num;
            cin >> num;
            a[i].push_back(num);
            mp[num] = i;
        }
    }
    sort(all(a));

    for (int i = 0; i < a.size(); i++) {
        for (auto num: a[i]) {
            temp.push_back(num);
        }
    }
    int cnt = 0;
    for (int i = 0; i < temp.size(); i++) {
        for (int j = i + 1; j < temp.size(); j++) {
            if (temp[j] < temp[i]) cnt++;
        }
    }
    k -= cnt;
    for (int i = 1; i < temp.size(); i++) {
        for (int j = i; j > 0; j--) {
            if (k > 0 && temp[j] > temp[j - 1] && mp[temp[j]] != mp[temp[j - 1]]) {
                cnt++;
                swap(temp[j], temp[j - 1]);
                k--;
            }
        }
    }
    if (k != 0) {
        cout << "No\n";
        return;
    }
    cout << "Yes\n";
    for (int i = 0; i < temp.size(); i++) cout << temp[i] << " \n"[i == temp.size() - 1];
}

signed main() {
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(0);
//    cout << fixed << setprecision(15);
    int _ = 1;
//    cin >> _;
    while (_--) {
        solve();
    }
    return 0;
}
posted @   yoez123  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示