1 条题解

  • 0
    @ 2023-8-30 16:31:00

    二分

    #include <bits/stdc++.h>
    using namespace std;
    const int MAXN = 100000;
    const int MAXM = 100000;
    int n, m;
    int a[MAXN + 5];
    int b[MAXM + 5];
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(0);
        cin >> n >> m;
        for (int i = 1; i <= n; i++)
            cin >> a[i];
        for (int i = 1; i <= m; i++)
            cin >> b[i];
        // work
        sort(a + 1, a + n + 1);
        long long ans = 0;
        for (int i = 1; i <= m; i++)
        {
            int pos = lower_bound(a + 1, a + n + 1, b[i]) - a;
            if (pos == 1)
                ans += abs(a[pos] - b[i]);
            else if (pos == n + 1)
                ans += abs(a[n] - b[i]);
            else
                ans += min(abs(a[pos] - b[i]), abs(a[pos - 1] - b[i]));
        }
        cout << ans << "\n";
        return 0;
    }
    

    双指针

    #include <bits/stdc++.h>
    using namespace std;
    const int MAXN = 100000;
    const int MAXM = 100000;
    int n, m;
    int a[MAXN + 5];
    int b[MAXM + 5];
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(0);
        cin >> n >> m;
        for (int i = 1; i <= n; i++)
            cin >> a[i];
        for (int i = 1; i <= m; i++)
            cin >> b[i];
        // work
        sort(a + 1, a + n + 1);
        sort(b + 1, b + m + 1);
        long long ans = 0;
        int pos = 1; // a[pos]>=b[i]
        for (int i = 1; i <= m; i++)
        {
            while (pos <= n && a[pos] < b[i])
                pos++;
            if (pos == 1)
                ans += abs(a[pos] - b[i]);
            else if (pos == n + 1)
                ans += abs(a[n] - b[i]);
            else
                ans += min(abs(a[pos] - b[i]), abs(a[pos - 1] - b[i]));
        }
        cout << ans << "\n";
        return 0;
    }
    
    • 1

    信息

    ID
    1318
    时间
    1000ms
    内存
    256MiB
    难度
    8
    标签
    递交数
    37
    已通过
    7
    上传者