CF #743 B. Swaps

思维题。两种写法,都是很棒的写法。和排序都有关,第一种没有直接排序,但是也有排序的思想。都是利用贪心,缩小了答案的范围。

#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e5 + 5, mod = 998244353;
int a[N], b[N];
struct node {
    int val, pos;
} a1[N], b1[N];
signed main()
{
    /* ios::sync_with_stdio(0);
    cin.tie(0); */
    int t;
    cin >> t;
    a[0] = 1e9 + 7;
    while(t--) {
        int n;
        scanf("%lld", &n);
        for (int i = 1; i <= n; i++) {
            scanf("%lld", &a[i]);
            a[i] = min(a[i], a[i - 1]);
        }
        for (int i = 1; i <= n; i++) scanf("%lld", &b[i]);
        int num = n;
        int ans = 1e9 + 7;
        for (int i = 1; i <= n; i++) {
            while(b[i] > a[num]) num--;
            ans = min(ans, num + i - 1);
        }
        cout << ans << endl;
    }
    return 0;
}

如果a [ i ] > b [ num ] 的话,那么b [ num ] 之前的数一定无法和 a [ i ] 之后的数进行匹配。

#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e5 + 5, mod = 998244353;
int b[N];
struct node {
    int val, pos;
    bool operator < (const node &k) const {
        return val < k.val;
    }
} a[N];
signed main()
{
    /* ios::sync_with_stdio(0);
    cin.tie(0); */
    int t;
    cin >> t;
    while(t--) {
        int n;
        scanf("%lld", &n);
        for (int i = 1; i <= n; i++) {
            scanf("%lld", &a[i].val);
            a[i].pos = i;
        }
        for (int i = 1; i <= n; i++) scanf("%lld", &b[i]);
        sort(a + 1, a + 1 + n);
        int ans = 1e9 + 7;
        int num = 1;
        for (int i = 1; i <= n; i++) {
            while(a[i].val > b[num]) num++;
            ans = min(ans, num - 1 + a[i].pos - 1);
        }
        cout << ans << endl;
    }
    return 0;
}
上一篇:查看SQL-SERVER数据库及各个表的数据量及占用空间大小


下一篇:Python - 操作 MySQL 数据库