Weight of the System of Nested Segments-Codeforces

投稿日: 更新日:

問題リンク-Weight of the System of Nested Segments

問題

数直線上にmm個の点があります。ii番目の点は位置xix_iに重みはwiw_iです。すべての点は異なる位置にあります。

整数nnが与えられるので以下の条件を満たす入れ子の区間を考えてください。

  • 区間の端点はmm個の与えられた点である。
  • 区間の端点になっている2n2n個の点の重みの総和が最小である。

解法

まず、重みが小さい順に点を選びます。その後、選んだ点の中からまだペアになっていない最右端の点と最左端の点をペアとしていけば良いです。
最右端の点と最左端の点を選ぶことによって区間を入れ子にできます。

実装

#include <bits/stdc++.h>
using namespace std;

struct Point{
    int i, x, w;
};

void solve(){
    int n, m;
    cin >> n >> m;
    vector<Point> xw;
    for(int i = 0;i < m; ++i){
        Point p;
        cin >> p.x >> p.w;
        p.i = i + 1;
        xw.push_back(p);
    }

    sort(xw.begin(), xw.end(), [](Point a, Point b){return a.w < b.w;});

    vector<Point> select;
    for(int i = 0;i < 2*n; ++i){
        select.push_back(xw[i]);
    }

    sort(select.begin(), select.end(), [](Point a, Point b){return a.x < b.x;});

    long long sum = 0;
    for(Point p : select){
        sum += p.w;
    }

    cout << sum << endl;
    for(int i = 0;i < n; ++i){
        cout << select[i].i << " " << select[2*n-1 - i].i << endl;
    }
    cout << endl;
}

int main(){
    int t;
    cin >> t;
    while(t--){
        solve();
    }
    return 0;
}

書いた人

profile_image

お茶の葉

物理とプログラミングが好きな人