【DFS】hdu 1584 蜘蛛牌

看代码:

#include <iostream>

#include <cstdio>

#include <fstream>



using namespace std;

const int INF=100000000;

const int MAXN=1000000;

int ans;

int pos[11];

bool vis[11];

int abs(int a,int b){

    if(a>b)return a-b;

    return b-a;

}

void dfs(int deep,int step){

    if(deep==9){

        if(step<ans)ans=step;

        return;

    }

    for(int i=1;i<10;i++){

        if(!vis[i]){

            vis[i]=1;

            for(int j = i+1;j<=10;j++)            {

                //如果vis[j]==0,那么j就已经移动到比j更大的牌上了

                

                if(!vis[j]){ //找到了i能移动到的位置。

                    int temp=step+abs(pos[i],pos[j]);

                    if(temp>ans)break;

                    dfs(deep+1,step+abs(pos[i],pos[j]));

                    break;

                }

            }

            vis[i]=0;

        }

    }

}

int main(){

    //freopen("in.txt","r",stdin);



    int t,n,m;

    scanf("%d",&t);

    while(t--){

        for(int i=1;i<=10;i++){

            int temp;

            scanf("%d",&temp);

            pos[temp]=i;

            vis[temp]=0;

        }

        ans=INF;

        dfs(0,0);

        printf("%d\n", ans);

    }

    return 0;

}

 

你可能感兴趣的:(HDU)