//\\__ hr1212 __//\\
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef map<int,int> mi;
#define si(a) scanf("%d",&a)
#define sii(a,b) scanf("%d %d",&a,&b)
#define siii(a,b,c) scanf("%d %d %d",&a,&b,&c)
#define pi(a) printf("%lld\n",a)
#define nl printf("\n");
#define pb push_back
#define mp make_pair
#define all(c) (c).begin(),(c).end()
#define f(i,a,b) for(i=a;i<b;i++)
#define rf(i,a,b) for(i=a;i>=b;i--)
#define clr(x,a) memset(x,a,sizeof(x))
#define MAX 1000100
#define MOD 1000000007
int n,m,mk[600],diff[600][600];
string p[10000];
priority_queue<pii > pq;
vi v[600];
void process(int x){
mk[x]=1;
int j,z,i;
f(j,1,n+1){
if(!mk[j] && j!=x)
pq.push(mp(-diff[x][j],-j));
}
}
int main(){
int r,k,i,c=0,x=0,y=0,j,t,l,x1=0,y1=0;
ll ans=0,z;
si(t);
while(t--){
si(n);
p[0]="0000";
f(i,1,n+1)
cin>>p[i];
f(i,0,n+1){
f(j,i+1,n+1){
y=0;
f(k,0,4){
int aa=p[i][k]-'0',bb=p[j][k]-'0';
y+=(min(abs(aa-bb),10-abs(aa-bb)));
}
diff[i][j]=y;
diff[j][i]=y;
}
}
z=1e9;
f(i,1,n+1){
if(diff[i][0]<z){
z=diff[i][0];
c=i;
}
}
pq.push(mp(-z,-c));
clr(mk,0);
ans=0;
while(!pq.empty()){
pii pp=pq.top();
pq.pop();
l=-pp.second;r=-pp.first;
if(!mk[l]){
ans+=r;
process(l);
}
}
pi(ans);
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef map<int,int> mi;
#define si(a) scanf("%d",&a)
#define sii(a,b) scanf("%d %d",&a,&b)
#define siii(a,b,c) scanf("%d %d %d",&a,&b,&c)
#define pi(a) printf("%lld\n",a)
#define nl printf("\n");
#define pb push_back
#define mp make_pair
#define all(c) (c).begin(),(c).end()
#define f(i,a,b) for(i=a;i<b;i++)
#define rf(i,a,b) for(i=a;i>=b;i--)
#define clr(x,a) memset(x,a,sizeof(x))
#define MAX 1000100
#define MOD 1000000007
int n,m,mk[600],diff[600][600];
string p[10000];
priority_queue<pii > pq;
vi v[600];
void process(int x){
mk[x]=1;
int j,z,i;
f(j,1,n+1){
if(!mk[j] && j!=x)
pq.push(mp(-diff[x][j],-j));
}
}
int main(){
int r,k,i,c=0,x=0,y=0,j,t,l,x1=0,y1=0;
ll ans=0,z;
si(t);
while(t--){
si(n);
p[0]="0000";
f(i,1,n+1)
cin>>p[i];
f(i,0,n+1){
f(j,i+1,n+1){
y=0;
f(k,0,4){
int aa=p[i][k]-'0',bb=p[j][k]-'0';
y+=(min(abs(aa-bb),10-abs(aa-bb)));
}
diff[i][j]=y;
diff[j][i]=y;
}
}
z=1e9;
f(i,1,n+1){
if(diff[i][0]<z){
z=diff[i][0];
c=i;
}
}
pq.push(mp(-z,-c));
clr(mk,0);
ans=0;
while(!pq.empty()){
pii pp=pq.top();
pq.pop();
l=-pp.second;r=-pp.first;
if(!mk[l]){
ans+=r;
process(l);
}
}
pi(ans);
}
return 0;
}
No comments:
Post a Comment