2018 蓝桥杯省赛 B 组模拟赛(五) 结果填空:藏宝图

bfs预处理两个点之间的距离,全排列求最短总路程.

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<algorithm>
#include<iostream>
#include<queue>
#include<map>
#include<cmath>
#include<set>
#include<stack>
#define ll long long
#define pb push_back
#define max(x,y) ((x)>(y)?(x):(y))
#define min(x,y) ((x)>(y)?(y):(x))
#define cls(name,x) memset(name,x,sizeof(name))
#define fs first
#define sc second
#define mp make_pair
#define L(x) (1<<x)
#define next Next
#define index Index
using namespace std;
const int inf=1e9+10;
const ll llinf=1e17+10;
const int maxn=1e1+10;
const int maxm=1e1+10;
const int mod=1e9+7;
int n;
int dist[maxn][maxn];
pair<int,int> p[maxn];
char mapp[maxn][maxn];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node
{
    int x,y;
    int cost;
};
int build(int stx,int sty,int edx,int edy)
{
    int vis[maxn][maxn];
    cls(vis,0);
    queue<node> Q;
    node temp;
    temp.x=stx; temp.y=sty;
    temp.cost=0;
    Q.push(temp);
    while(!Q.empty())
    {
        temp=Q.front();
        Q.pop();
        vis[temp.x][temp.y]=1;
        if(temp.x==edx&&temp.y==edy)
            return temp.cost;
        for(int i=0;i<4;i++)
        {
            node next=temp;
            next.x+=dir[i][0];
            next.y+=dir[i][1];
            next.cost++;
            if(next.x<0||next.y<0||next.x>9||next.y>9||vis[next.x][next.y]||mapp[next.x][next.y]=='x')
                continue;
            Q.push(next);
        }
    }
}
void solve()
{

}
int main()
{
    //freopen("in.txt","r",stdin);
    while(~scanf("%d",&n))
    {
        for(int i=0;i<=9;i++)
            scanf("%s",mapp[i]);
        int k=0;
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
            {
                if(mapp[i][j]>='0'&&mapp[i][j]<='9')
                    p[k++]=mp(i,j);
            }
        p[k]=mp(0,0);
        build(p[0].fs,p[0].sc,p[1].fs,p[1].sc);
        for(int i=0;i<=k;i++)
        {
            for(int j=i+1;j<=k;j++)
            {
                dist[i][j]=dist[j][i]=build(p[i].fs,p[i].sc,p[j].fs,p[j].sc);
            }
        }
        int a[]={0,1,2,3,4,5,6,7,8,9};
        int ans=inf;
        do
        {
            int s=dist[10][a[0]]+dist[a[9]][10];
            for(int i=0;i<=8;i++)
            {
                s+=dist[a[i]][a[i+1]];
            }
            ans=min(ans,s);
        }while(next_permutation(a,a+10));
        printf("%d\n",ans);
    }
    return 0;
}

  

posted @ 2018-03-26 19:19  爱种树的码农  阅读(424)  评论(0编辑  收藏  举报