蜘蛛牌
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3716 Accepted Submission(s): 1586
Problem Description
蜘蛛牌是windows xp操作系统自带的一款纸牌游戏,游戏规则是这样的:只能将牌拖到比她大一的牌上面(A最小,K最大),如果拖动的牌上有按顺序排好的牌时,那么这些牌也跟着一起移动,游戏的目的是将所有的牌按同一花色从小到大排好,为了简单起见,我们的游戏只有同一花色的10张牌,从A到10,且随机的在一行上展开,编号从1到10,把第i号上的牌移到第j号牌上,移动距离为abs(i-j),现在你要做的是求出完成游戏的最小移动距离。
Input
第一个输入数据是T,表示数据的组数。
每组数据有一行,10个输入数据,数据的范围是[1,10],分别表示A到10,我们保证每组数据都是合法的。
每组数据有一行,10个输入数据,数据的范围是[1,10],分别表示A到10,我们保证每组数据都是合法的。
Output
对应每组数据输出最小移动距离。
Sample Input
1 1 2 3 4 5 6 7 8 9 10
Sample Output
9
Author
xhd
Source
Recommend
起初队友一直说是贪心。。于是我也用贪心水了一发
果然Wa..
于是就用万能的搜索了。
搜索难点就在于怎么去重。也就是判断某种序列已经使用过了。
我用的是set容器。里面放string检测。把1~10十个数字当作字符来存。
在使用bfs之前,我们要明确一个问题。
纸牌的放置规则:只能将牌拖到比她大一的牌上面(A最小,K最大),如果拖动的牌上有按顺序排好的牌时,那么这些牌也跟着一起移动
根据这个规则,我们就可以知道对于某一个位置上的所有牌,我们只要存贮它的最上面的一张牌和最下面的一张牌即可。
当需要移动某个位置a,b牌时:
- a->b:判断a.top-b.bottom是否为1,如果为1,证明可以移动,移动后更新b.bottom=a.top
代码:
#include <stdio.h>
#include <string.h>
#include <queue>
#include <set>
#include <iostream>
using namespace std;
char str[15];
struct node
{
char str[15];
char top[15];
char bottom[15];
int cost;
int count;
friend bool operator<(node a,node b)
{
return a.cost>b.cost;
}
};
int bfs()
{
priority_queue<node>s;
set<string>ss;
ss.clear();
node node1,node2;
node1.cost=node1.count=0;
strcpy(node1.str,str);
strcpy(node1.top,str);
strcpy(node1.bottom,str);
s.push(node1);
while(!s.empty())
{
node2=node1=s.top();s.pop();
if(node1.count==9) return node1.cost;
if(ss.find(node1.str)!=ss.end()) continue;
ss.insert(node1.str);
for(int r=1;r<10;r++)
{
for(int i=0;i<10;i++)
{
if(node1.str[i]=='-'||node1.str[i+r]=='-') continue;
if(node1.bottom[i]-node1.top[i+r]==1||node1.top[i]-node1.bottom[i+r]==-1)
{
node1.cost+=r;
node1.count++;
if(node1.top[i]-node1.bottom[i+r]==-1)
{
node1.bottom[i+r]=node1.bottom[i];
node1.str[i]='-';
}
else
{
node1.bottom[i]=node1.bottom[i+r];
node1.str[i+r]='-';
}
if(ss.find(node1.str)==ss.end())
s.push(node1);
node1=node2;
}
}
}
}
}
int main()
{
int t;
// freopen("in.txt","r",stdin);
scanf("%d",&t);
while(t--)
{
for(int i=0;i<10;i++)
{
int a;
scanf("%d",&a);
str[i]=a+'0';
}
str[10]='\0';
printf("%d\n",bfs());
}
return 0;
}