蜘蛛牌
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1476 Accepted Submission(s): 569
Problem Description
蜘蛛牌是windows xp操作系统自带的一款纸牌游戏,游戏规则是这样的:只能将牌拖到比她大一的牌上面(A最小,K最大),如果拖动的牌上有按顺序排好的牌时,那么这些牌也跟着一起移动,游戏的目的是将所有的牌按同一花色从小到大排好,为了简单起见,我们的游戏只有同一花色的10张牌,从A到10,且随机的在一行上展开,编号从1到10,把第i号上的牌移到第j号牌上,移动距离为abs(i-j),现在你要做的是求出完成游戏的最小移动距离。
Input
第一个输入数据是T,表示数据的组数。
每组数据有一行,10个输入数据,数据的范围是[1,10],分别表示A到10,我们保证每组数据都是合法的。
Output
对应每组数据输出最小移动距离。
Sample Input
1 1 2 3 4 5 6 7 8 9 10
Sample Output
9
用数组把每个数字在哪个位置记录下来,然后爆搜就行,注意剪枝,因为我要求的是移动最快的,所以当你移动一步的时候要判断是否比已经出来的方案更慢,更慢的话我肯定不用再继续了,对啵?
#include <iostream> using namespace std; int s,x[11],visit[11]; int cmp(int a,int b) //求绝对值 { return a>b?a-b:b-a; } void dfs(int n,int step) { int i,j,k; if(n==9) { if(step<s)s=step; return; } for(i=0;i<10;i++) //用来移动的牌 if(!visit[i]) for(j=i+1;j<10;j++) //移动到那个位置 { if(!visit[j]) { k=step+cmp(x[i],x[j]); if(k>=s)break; //如果还没到终点就已经比先前的方案步数多,那么直接over visit[i]=1; //标记当前移动的牌已经就位了,因为i到了j的位置了,那么移动j就不管i的鸟事了 dfs(n+1,k); visit[i]=0; break; } } } int main (void) { int i,j,k,l,n,a; cin>>n; while(n--) { for(i=0;i<10;i++) cin>>a,x[a-1]=i,visit[i]=0; //用x记录每个牌出现的位置 s=999999999; dfs(0,0); cout<<s<<endl; } return 0; }
HDU--1584--蜘蛛牌--深搜版本
时间: 2024-08-23 20:55:30