Submission #93515

#TimeUsernameProblemLanguageResultExecution timeMemory
93515arafat_01Stove (JOI18_stove)C++17
100 / 100
54 ms2744 KiB
#include <bits/stdc++.h>

#define F first
#define S second
#define mp make_pair
#define pb push_back
#define sz(x) (int)x.size()
//#define int ll

using namespace std;

typedef long long ll;
typedef long double ld;

const int N = (int)4e5 + 123;
const int mod = 1e9 + 7;
const ll inf = 1e18 + 9;

inline void boost () {
	ios_base::sync_with_stdio (0);
	cin.tie (0), cout.tie (0);
}
int n, k, t[N], pr[N], sz[N], all = n;
ll sum;

int get (int x) {
	if (x == pr[x]) return x;
	return pr[x] = get (pr[x]);
}

void unite (int u, int v, int c) {
	if (all == k) cout << sum, exit (0);
	u = get (u), v = get (v);
	if (u == v) return;
	if (sz[u] < sz[v]) swap (u, v);
	sz[u] += sz[v];
	pr[v] = u;
	sum += c; 
	all --;
	if (all == k) cout << sum, exit (0);
}

int main () {
	boost ();
	cin >> n >> k;
	all = n, sum = k;
	for (int i = 1;i <= n;i ++) {	
		cin >> t[i];
		pr[i] = i, sz[i] = 1;
	}
	vector < pair < int, int > > v;
	for (int i = 2;i <= n;i ++) v.pb (mp (t[i] - t[i - 1], i - 1));		
	sort (v.begin (), v.end ());
	for (int i = 0;i < sz (v);i ++) {
		int u = v[i].S;
		int u1 = u + 1;
		int c = v[i].F;
		unite (u, u1, c);
	}
	cout << sum;
	return 0;
}                                
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...