蜘蛛牌 (DFS)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1584

 

 

全部状态都判断一遍

 

代码:

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <math.h>
 4 #include <algorithm>
 5 #include <iostream>
 6 #include <ctype.h>
 7 #include <iomanip>
 8 #include <queue>
 9 #include <stdlib.h>
10 using namespace std;
11 
12 int ans;
13 int tep[11],vis[11];
14 
15 int abs(int x)
16 {
17     if(x>=0)
18         return x;
19     return -x;
20 }
21 
22 void dfs(int cnt,int sum)
23 {
24     if(sum >= ans)
25         return ;
26     if(cnt==9){
27         ans=sum;
28         return ;
29     }
30     for(int i=1; i<10; i++){
31         if(!vis[i]){
32             vis[i]=1;
33             for(int j=i+1; j<=10; j++){
34                 if(!vis[j]){
35                     dfs(cnt+1,sum+abs(tep[i]-tep[j]));
36                     break;
37                 }
38             }
39             vis[i]=0;
40         }
41     }
42 }
43 
44 int main()
45 {
46     int t,x;
47     scanf("%d",&t);
48     while(t--){
49         for(int i=1; i<=10; i++){
50             scanf("%d",&x);
51             tep[x]=i;
52         }
53         memset(vis,0,sizeof(vis));
54         ans=10000000;
55         dfs(0,0);
56         printf("%d\n",ans); 
57     }
58 }

 

posted @ 2016-03-06 14:48  Vmetrio  阅读(293)  评论(0编辑  收藏  举报