codeforce 677D Vanya and Treasure

原题地址:http://codeforces.com/problemset/problem/677/D

 

题意

 

题解

直接的DP是n2m2的复杂度,据题解说通过bfs来转移可以实现n*m*sqrt(n*m)……

 

#include<bits/stdc++.h>

#define clr(x,y) memset((x),(y),sizeof(x))

using namespace std;
typedef long long LL;

const int maxn=300;

struct Cood
{
    int x;
    int y;
};

vector <Cood> G[maxn*maxn+5];
queue<Cood> Q;

int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
int dp[maxn+5][maxn+5];
int temp[maxn+5][maxn+5];
bool book[maxn+5][maxn+5];

int main(void)
{
    #ifdef ex
    freopen ("../in.txt","r",stdin);
    //freopen ("../out.txt","w",stdout);
    #endif

    int n,m,p;
    scanf("%d%d%d",&n,&m,&p);

    clr(dp,127);
    int a;
    for (int i=1;i<=n;++i)
    {
        for (int j=1;j<=m;++j)
        {
            scanf("%d",&a);
            G[a].push_back((Cood){i,j}); /*****/
            if (a==1) dp[i][j]=i+j-2;
        }
    }

    int k=sqrt(n*m);

    for (int i=2;i<=p;++i)
    {
        if (G[i].size()<k)
        {
            for (auto g1:G[i])
            {
                for (auto g2:G[i-1])
                {
                    dp[g1.x][g1.y]=min(dp[g1.x][g1.y],dp[g2.x][g2.y]+abs(g1.x-g2.x)+abs(g1.y-g2.y));
                }
            }
        }

        else
        {
            clr(temp,127); //全部初始化为MAX_INT
            clr(book,0);
            for (auto g:G[i-1])
            {
                Q.push(g);
                temp[g.x][g.y]=dp[g.x][g.y];
            }

            while (!Q.empty()) //***********//
            {
                Cood now=Q.front();
                Q.pop();
                book[now.x][now.y]=false;
                for (int i=0;i<=3;++i)
                {
                    Cood tmp;
                    tmp.x=now.x+dx[i];
                    tmp.y=now.y+dy[i];
                    if (tmp.x<1 || tmp.x>n || tmp.y<1 || tmp.y>m) continue;
                    if (temp[tmp.x][tmp.y]>temp[now.x][now.y]+1)
                    {
                        temp[tmp.x][tmp.y]=temp[now.x][now.y]+1;
                        if (!book[tmp.x][tmp.y])
                        {
                            book[tmp.x][tmp.y]=true;
                            Q.push(tmp);
                        }
                    }
                }
            }

            for (auto g:G[i])
                dp[g.x][g.y]=temp[g.x][g.y];
        }
    }

    Cood &ans=G[p][0];
    printf("%d\n",dp[ans.x][ans.y]);
}

/* http://codeforces.com/problemset/problem/677/D */

 

转载于:https://www.cnblogs.com/123-123/p/5579283.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值