1489: 数字排列
http://www.acmore.net/problem.php?id=1489
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 213 Solved: 77
Description
小Y得到了一个数,他认为相邻位上的数字与数字之间会产生不良影响,比如123,1和2之间产生一个不良影响值,2和3之间产生一个不良影响值。现在他想调整这个数每位的数字的顺序,使得最终得到的数的总的不良影响值最小,且没有前导0。
Input
输入数据的第一行为T表示有T组数据。每组数据先输入一个整数n(0<n<1000000000),接下来输入10*10的矩阵,Aij表示数字i与数字j相邻产生的不良影响值,0<Aij<1000000,矩阵是对称的,Aij与Aji相等。
Output
对于每组数据输出一行一个数,表示最小的不良影响值。
Sample Input
1
123
0 0 0 0 0 0 0 0 0 0
0 0 10 1 0 0 0 0 0 0
0 10 0 2 0 0 0 0 0 0
0 1 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
Sample Output
3
HINT
Source
#include<iostream> #include<cstdio> #include<cstring> #include<vector> using namespace std; const int INF=0x3f3f3f3f; int a[15],b[15],vis[15],val[15][15]; int len,ans; void DFS(int loc,int sum){ if(sum>ans) return ; if(loc==len){ if(ans>sum) ans=sum; return ; } for(int i=0;i<len;i++) if(!vis[i]){ if(loc==0){ if(a[i]==0) //第一位不能放0 continue; vis[i]=1; b[loc]=a[i]; DFS(loc+1,0); vis[i]=0; }else{ if(sum+val[a[i]][b[loc-1]]<ans){ //减枝 vis[i]=1; b[loc]=a[i]; DFS(loc+1,sum+val[a[i]][b[loc-1]]); vis[i]=0; } } } } int main(){ //freopen("input.txt","r",stdin); int t,n; scanf("%d",&t); while(t--){ scanf("%d",&n); for(int i=0;i<10;i++) for(int j=0;j<10;j++) scanf("%d",&val[i][j]); int tmp=n; len=0; while(tmp){ a[len++]=tmp%10; tmp/=10; } memset(vis,0,sizeof(vis)); ans=INF; DFS(0,0); printf("%d\n",ans); } return 0; }