AT wtf22 day2C Jewel Pairs

· · 个人记录

题目描述

有 n 个宝石,每个宝石有 (c_i,v_i) (颜色,价值). 2 个宝石 (i,j) 被称为好的当且仅当。

你打算从N个宝石中选择几个好的组合。1个宝石不能重复使用两次以上,但可以不使用。请求出组合中包含的所有宝石的价值的总和可能的最大值。

题解

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 300000;
typedef long long ll;
struct node { int c;ll w; };
bool cmp(const node& a, const node& b)
{
    if (a.w == b.w)return a.c < b.c; return a.w < b.w;
}
int n, ma[N], lst[N], scnt[N]; ll L;
pair<vector<node>, vector<node>> match(vector<node> a, int& id, int& odd)
{
    int s = 0, b = 0;
    vector<node> mat, oth;
    for (int i = 1;i <= n;i++)ma[i] = lst[i] = scnt[i] = 0;
    for (auto p : a)
    {
        auto [c, w] = p;
        if (c > n)
        {
            c -= n;ma[c] = min(scnt[c], ma[c] + b - lst[c]);
            if ((s - scnt[c]) - (b - ma[c]) <= 0)
                oth.push_back(p);
            else mat.push_back(p), b++; lst[c] = b;
        }
        else
        {
            c += n; ma[c] = min(scnt[c], ma[c] + b - lst[c]);
            lst[c] = b; s++; scnt[c]++; mat.push_back(p);
        }
    }
    int sum = s - b; id = -1, odd = 0;
    for (int c = 1;c <= n;c++)
    {
        ma[c] = min(scnt[c], ma[c] + b - lst[c]);
        int mi = scnt[c] - ma[c];
        if (mi * 2 > sum) { id = c;odd = 2 * mi - sum; }
    }
    if (id == -1)odd = sum & 1; return { mat,oth };
}
void solve()
{
    cin >> n >> L;
    vector<node> a, b;
    for (int i = 1;i <= n;i++)
    {
        int c, w; cin >> c >> w;
        if (w * 2 <= L)a.push_back({ c - n,w });
        else a.push_back({ c + n,L - w });
    }
    int id, odd; sort(a.begin(), a.end(), cmp);
    a = match(a, id, odd).first; reverse(a.begin(), a.end());
    ll ans = 0;
    for (auto [c, w] : a)
    {
        if (c > n)
        {
            ans += L - w;b.push_back({ c - n - n,L - w });
        }
        else
        {
            ans += w;
            if (id == -1 || id == c + n)
                b.push_back({ c + n + n,L - w });
        }
    }
    b = match(b, id, id).second;reverse(b.begin(), b.end());
    for (int i = 0;i < odd;i++)ans -= L - b[i].w;
    cout << ans << '\n';
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);cout.tie(nullptr);
    solve();
    return 0;
}