結果

問題 No.2543 Many Meetings
ユーザー kwm_tkwm_t
提出日時 2023-12-30 01:44:36
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 148 ms / 2,000 ms
コード長 2,525 bytes
コンパイル時間 2,451 ms
コンパイル使用メモリ 207,676 KB
最終ジャッジ日時 2025-02-18 15:23:34
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 40
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
//#include <atcoder/all>
using namespace std;
//using namespace atcoder;
//using mint = modint998244353;
//const int mod = 998244353;
//using mint = modint1000000007;
//const int mod = 1000000007;
const int INF = 1e9;
//const long long LINF = 1e18;
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rep2(i,l,r)for(int i=(l);i<(r);++i)
#define rrep(i, n) for (int i = (n-1); i >= 0; --i)
#define rrep2(i,l,r)for(int i=(r-1);i>=(l);--i)
#define all(x) (x).begin(),(x).end()
#define allR(x) (x).rbegin(),(x).rend()
#define P pair<int,int>
template<typename A, typename B> inline bool chmax(A & a, const B & b) { if (a < b) { a = b; return true; } return false; }
template<typename A, typename B> inline bool chmin(A & a, const B & b) { if (a > b) { a = b; return true; } return false; }
bool chk(const vector<P> &v, int k) {
	int pre = 0;
	int cnt = 0;
	rep2(i, 1, v.size()) {
		if (v[pre].second <= v[i].first) {
			cnt++;
			pre = i;
		}
	}
	return cnt >= k;
}
vector<int> calcNext(const vector<P> &d,int n) {
	vector<int>next(n, -1);
	struct SubD {
		int l, r, idx;
		SubD() {};
		SubD(int l, int r, int idx) : l(l), r(r), idx(idx) {};
	};
	vector<SubD>subD(n);
	rep(i, n) {
		subD[i] = SubD(d[i].first, d[i].second, i);
	}
	int mn = INF;
	int idx = -1;
	sort(all(subD), [](const SubD x, const SubD &y) {return x.l < y.l; });
	rrep(i, n) {
		while (!subD.empty() && d[i].second <= subD.back().l) {
			auto top = subD.back();
			if (chmin(mn, top.r))idx = top.idx;
			subD.pop_back();
		}
		next[i] = idx;
	}
	return next;
}
int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int n, k; cin >> n >> k;
	vector<P>d(n);
	rep(i, n)cin >> d[i].first >> d[i].second;
	sort(all(d), [](const P x, const P &y) {return x.second < y.second; });
	if (!chk(d, k)) {
		cout << -1 << endl;
		return 0;
	}
	// dp[i][j]:=iから初めて2^j個数選ぶ時の最後に選んだindex
	vector dp(n, vector<int>(20, -1));
	auto next = calcNext(d, n);
	rep(i, n)dp[i][0] = next[i];
	rep2(i, 1, 20) {
		rep(j, n) {
			int x0 = dp[j][i - 1];
			if (-1 == x0)continue;
			int x1 = dp[x0][i - 1];
			dp[j][i] = x1;
		}
	}
	k--;
	int ans = INF;
	rep(i, n) {
		int ck = k;
		int ci = i;
		bool chk = true;
		rep(j, 20) {
			if (1 == ck % 2) {
				if (-1 == ci) {
					chk = false;
					break;
				}
				ci = dp[ci][j];
				if (-1 == ci) {
					chk = false;
					break;

				}
			}
			ck /= 2;
		}
		if (chk) {
			int val = d[ci].second - d[i].first;
			chmin(ans, val);
		}
	}
	cout << ans << endl;
	return 0;
}
0