#include <bits/stdc++.h>
#define N 1000005
using namespace std;
int n,k;
int val[N];
int par[N];
int l[N],r[N];
int len[N];
int find(int a){
if(par[a] == a)return a;
return par[a] = find(par[a]);
}
void merge(int a,int b){
a = find(a);
b = find(b);
if(a == b)return;
if(val[a] != val[b])return;
par[b] = a;
r[a] = r[b];
len[a] += len[b];
len[b] = 0;
}
bool ck(int x){
if(len[x] == 0)return 0;
if(val[find((l[x] - 1 + n)%n)] <= val[x])return 0;
if(val[find((r[x] + 1 + n)%n)] <= val[x])return 0;
return 1;
}
void solve(){
cin >> n >> k;
for(int i=0;i<n;i++){
par[i] = l[i] = r[i] = i;
len[i] = 1;
cin >> val[i];
}
for(int i=0;i<n;i++){
merge(i, (i + 1)%n);
}
set<pair<int,int>> s;
for(int i=0;i<n;i++){
if(ck(i)){
s.insert({len[i],i});
}
}
long long ans = 0;
while(s.size() && k >= s.begin()->first){
auto [ln,x] = *s.begin();
s.erase(s.begin());
int num = min(val[find((l[x] - 1 + n)%n)]-val[x],val[find((r[x] + 1 + n)%n)] - val[x]);
num = min(num,k/ln);
val[x] += num;
k -= num*ln;
//cout << x << " " << l[x] << " " << r[x] << " " << len[x] <<" " << val[x]<< endl;
merge((l[x] - 1 + n)%n,x);
merge(x,(r[x] + 1 + n)%n);
x = find(x);
if(ck(x)){
s.insert({len[x],x});
}
ans += num * 2;
}
cout << ans << endl;
}
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
#ifdef Local
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
int t=1;
//cin>>t;
while(t--){
solve();
}
#ifdef Local
cout<<endl<<fixed<<setprecision(2)<<1000.0 * clock() / CLOCKS_PER_SEC<< " milliseconds ";
#endif
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
332 KB |
Output is correct |
2 |
Correct |
1 ms |
332 KB |
Output is correct |
3 |
Correct |
1 ms |
332 KB |
Output is correct |
4 |
Correct |
1 ms |
332 KB |
Output is correct |
5 |
Correct |
0 ms |
332 KB |
Output is correct |
6 |
Correct |
0 ms |
332 KB |
Output is correct |
7 |
Correct |
1 ms |
332 KB |
Output is correct |
8 |
Correct |
1 ms |
352 KB |
Output is correct |
9 |
Correct |
1 ms |
332 KB |
Output is correct |
10 |
Correct |
12 ms |
3148 KB |
Output is correct |
11 |
Correct |
20 ms |
4848 KB |
Output is correct |
12 |
Correct |
15 ms |
3148 KB |
Output is correct |
13 |
Correct |
113 ms |
29416 KB |
Output is correct |
14 |
Correct |
117 ms |
29380 KB |
Output is correct |
15 |
Correct |
95 ms |
27404 KB |
Output is correct |
16 |
Correct |
113 ms |
28468 KB |
Output is correct |
17 |
Correct |
101 ms |
28360 KB |
Output is correct |
18 |
Correct |
103 ms |
29176 KB |
Output is correct |
19 |
Correct |
105 ms |
29376 KB |
Output is correct |
20 |
Correct |
95 ms |
25732 KB |
Output is correct |