提交时间:2021-05-27 22:15:20

运行 ID: 20030

#include<bits.stdc++.h> using namespace std; int a[21],b[21],used[21],ans=10000,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; }