提交时间:2021-05-27 21:53:45

运行 ID: 20015

#include<iostream> #include<cmath> using namespace std; int a[21],b[21],used[21],ans=10000; int n,k; void check() { int x,y,i,sum=0; x=b[1]/10; y=b[1]%10; sum=abs(x-y); for(i=2;i<=n;++i){ x=y; y=b[i]/10; sum+=abs(x-y); x=y; y=b[i]%10; sum+=abs(x-y); } if(sum<ans)ans=sum; } void dfs(int t) { if(t==n){check();return;} else for(int i=1;i<=n;i++){ if(a[used[i]])continue; b[t+1]=a[i]; used[i]=1; dfs(t+1); used[i]=0; } } int main() { cin>>n; for(int i=1;i<=n;i++) cin>>a[i]; dfs(0); cout<<ans; return 0; }