10642 | 2024-04-07 16:34:58 | 111 | Kicsi billentyűzet | cpp17 | Accepted 100/100 | 68ms | 4392 KiB |
#include<bits/stdc++.h>
using namespace std;
#define int long long
signed main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T;
cin>>T;
while(T--){
string S;
cin>>S;
int N=S.size();
S='0'+S;
for(char&c:S){
c-='0';
}
int tot=0;
int cnt[10][10]{};
for(int i=1;i<=N;i++){
int s=min(S[i],S[i-1]);
int e=max(S[i],S[i-1]);
cnt[s][e]++;
tot+=e-s;
}
auto calc=[&](int p)->int{
int b=0;
for(int i=0;i<10;i++){
for(int j=i+1;j<10;j++){
int a=0;
for(int k=0;k<i;k++){
a+=(cnt[k][j]-cnt[k][i])*(j-i);
}
for(int k=j+1;k<10;k++){
a+=(cnt[i][k]-cnt[j][k])*(j-i);
}
for(int k=i+1;k<j;k++){
a+=(cnt[i][k]-cnt[k][j])*((k-i)-(j-k));
}
if(i==S[p]){
a+=abs(i-S[p-1]);
a-=abs(j-S[p-1]);
}
if(j==S[p]){
a+=abs(j-S[p-1]);
a-=abs(i-S[p-1]);
}
b=max(b,a);
}
}
return tot-b;
};
int ans=N*10;
for(int i=1;i<=N;i++){
int s=min(S[i],S[i-1]);
int e=max(S[i],S[i-1]);
cnt[s][e]--;
ans=min(ans,calc(i));
}
cout<<ans<<'\n';
}
return 0;
}
Subtask | Sum | Test | Verdict | Time | Memory | ||
---|---|---|---|---|---|---|---|
subtask1 | 0/0 | ||||||
1 | Accepted | 3ms | 1824 KiB | ||||
2 | Accepted | 3ms | 2060 KiB | ||||
subtask2 | 30/30 | ||||||
3 | Accepted | 3ms | 2284 KiB | ||||
4 | Accepted | 65ms | 2648 KiB | ||||
5 | Accepted | 63ms | 2740 KiB | ||||
6 | Accepted | 63ms | 2800 KiB | ||||
7 | Accepted | 63ms | 3184 KiB | ||||
8 | Accepted | 63ms | 3716 KiB | ||||
9 | Accepted | 64ms | 3744 KiB | ||||
subtask3 | 30/30 | ||||||
10 | Accepted | 3ms | 3308 KiB | ||||
11 | Accepted | 3ms | 3312 KiB | ||||
12 | Accepted | 3ms | 3412 KiB | ||||
13 | Accepted | 3ms | 3408 KiB | ||||
14 | Accepted | 3ms | 3540 KiB | ||||
subtask4 | 40/40 | ||||||
15 | Accepted | 28ms | 3628 KiB | ||||
16 | Accepted | 68ms | 3692 KiB | ||||
17 | Accepted | 64ms | 3848 KiB | ||||
18 | Accepted | 64ms | 3692 KiB | ||||
19 | Accepted | 64ms | 3800 KiB | ||||
20 | Accepted | 64ms | 4044 KiB | ||||
21 | Accepted | 64ms | 4236 KiB | ||||
22 | Accepted | 64ms | 4392 KiB | ||||
23 | Accepted | 64ms | 4160 KiB |