VK Cup 2017 - Qualification 1 C 贪心

是一道很有趣的题目 

给出地图和起始点 与要求的步数k 要求走k步 正好回到起始点 输出字典序最小的移动路径 DLRU这样

可以想到DU LR都是相同数量的 于是k必须是一个偶数

然后走了弯路QAQ 从这个地方入手 可以想到贪心按顺序DLRU去四个方向挨个跑 跑k/2次 然后原路返回 

然而因为走了k/2步之后 可能接着DLRU走回去 所以原路返回可能不是最优的 但是k是1e6 肯定不能dfs

后来发现可以bfs处理一下起始点到每个点的最短距离 代表从这个点走到起始点最少多少步

然后每一步都去贪心的走 但是要看剩余步数能不能回去

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<map>
#include<iostream>
#include<string>
#include<vector>
#include<queue>
using namespace std;
#define L long long

char ans[1000050] ;
int n , m , q ;
char s[1050][1050] ;

char z[4] = {'D' , 'L' , 'R' , 'U'} ;
int dx[4] = {1,0,0,-1} ;
int dy[4] = {0,-1,1,0} ;

int dis[1050][1050] ;

void bfs(int sx , int sy){
    dis[sx][sy]=0;
    queue<pair<int ,int > > que;
    que.push(make_pair(sx,sy) ) ;
    while(!que.empty()) {
        pair<int ,int > u = que.front() ; que.pop() ;
        for(int i = 0 ; i < 4 ; i ++ ) {
            int nx = u.first + dx[i] ;
            int ny = u.second + dy[i] ;
            int t = dis[u.first][u.second] + 1 ;
            if(nx <= n && ny >= 1 && ny <= m && s[nx][ny] != '*' && dis[nx][ny] > t && nx >= 1) {
                dis[nx][ny] = t ;
                que.push(make_pair(nx,ny) ) ;
            }
        }
    }
}

int main(){
    scanf("%d%d%d" , &n, &m , &q) ;
    for(int i=1;i<=n;i++)scanf("%s",s[i]+1);
    if(q%2==1){
        printf("IMPOSSIBLE\n");
        return 0;
    }
    for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)dis[i][j] = 999999999 ;
    int sx,sy;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            if(s[i][j]=='X')bfs(i,j),sx=i,sy=j;
        }
    }
    int cnt = 0 ;
    while(cnt < q) {
        cnt ++ ;
        int i ;
        for(i = 0 ; i < 4 ; i ++ ){
            int nx = sx+dx[i];
            int ny = sy+dy[i];
            if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && s[nx][ny] != '*' && dis[nx][ny] <= q - cnt) {
                sx = nx ;
                sy = ny ;
                ans[cnt]=z[i];
                break ;
            }
        }
        if(i == 4) {
            cnt = -1 ;
            break ;
        }
    }
    if(cnt == -1) printf("IMPOSSIBLE\n");
    else {
        for(int i=1;i<=cnt;i++)printf("%c",ans[i]);
        printf("\n");
    }
}

  

转载于:https://www.cnblogs.com/rayrayrainrain/p/6594788.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值