P酱的冒险旅途(思维)

P酱的冒险旅途

Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others)
 

P酱是个可爱的男孩子,有一天他在野外冒险,不知不觉中走入了一块神奇的地方。他在0时刻进入这个地方,每一时刻他都只能向某一特定的方向移动长度为1的距离,当然他也可以选择不移动。移动需要花费1的时间。

各个时刻他允许移动的方向由一个字符串给出,字符串只包含UDLR四种字符,其中U表示向上(y轴正方向)移动,D表示向下(y轴负方向)移动,L表示向左(x轴负方向)移动,R表示向右(x轴正方向)移动。

字符串的第x个字符代表了第x时刻P酱可以移动的方向,字符串的长度只有t,也就是说,超过t时刻,P酱就要被邪恶的魔王大爷抓走了~

现在P酱在坐标原点,即(0,0)点,而出口在(x,y)点,P酱希望在规定的时间t内尽快走到出口。帮助P酱在最短的时间内离开这里吧~

Input

第一行包含一个正数 T (T100),表示数据组数。

接下来每组数据包含两行,第一行包含三个整数 x,y,t (105x,y105,0<t105);第二行包含一个长度为t的字符串,第i个字符表示在i时刻他能移动的方向,字符串只包含UDLR四种字母。

Output

对于每组数据输出一行,表示P酱到达出口的最早时刻。如果他无法在t时刻内到达出口,输出-1

Sample input and output

Sample InputSample Output
2
1 -1 5
LDRDR
-2 1 8
RRUDDLRU
3
-1

Hint

第一组样例:

  1. P酱在0时刻位于原点(0,0),他只能向左移动,但他选择不走。
  2. P酱在1时刻依然位于原点(0,0),他只能向下移动,于是他向下移动到了(0,1)
  3. P酱在2时刻位于(0,1),他只能向右移动,于是他移动到了出口(1,1),所以在3时刻,P酱离开了这片区域!

题解:受着上题的影响,于是苦逼的我果断暴力了(想都没想);然后结果可想而知,肯定超时了。10的5次方,每次两种选择,也就是2的10万次方,不超时才算有鬼了;

没浪费时间直接按照题意写了下,就A了;

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
#define mem(x,y) memset(x,y,sizeof(x))
#define SI(x) scanf("%d",&x)
#define PI(x) printf("%d",x)
#define P_ printf(" ")
const int INF=0x3f3f3f3f;
const int MAXN=1e5+100;
char s[MAXN];
int x,y,t;
int main(){
    int T;
    SI(T);
    while(T--){
        scanf("%d%d%d",&x,&y,&t);
        scanf("%s",s+1);
        int ans=0,nx=0,ny=0,flot=0;
        for(int i=1;s[i];i++,ans++){
            if(x==nx&&y==ny){
                flot=1;break;
            }
            if(s[i]=='L'){
                if(x<=0&&nx>x)nx--;
            }
            if(s[i]=='R'){
                if(x>=0&&nx<x)nx++;
            }
            if(s[i]=='U'){
                if(y>=0&&ny<y)ny++;
            }
            if(s[i]=='D'){
                if(y<=0&&ny>y)ny--;
            }
        }
        if(flot)printf("%d
",ans);
        else puts("-1");
    }
    return 0;
} 

暴力超时了,也贴下吧:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
#define mem(x,y) memset(x,y,sizeof(x))
#define SI(x) scanf("%d",&x)
#define PI(x) printf("%d",x)
#define P_ printf(" ")
const int INF=0x3f3f3f3f;
const int MAXN=1e5+100;
char s[MAXN];
int x,y,t;
int ans;
void dfs(int nx,int ny,int cur){
    if(cur>t)return;
    if(nx==x&&ny==y){
        ans=min(ans,cur-1);
        return;
    }
    dfs(nx,ny,cur+1);
    if(s[cur]=='L')dfs(nx-1,ny,cur+1);
    if(s[cur]=='R')dfs(nx+1,ny,cur+1);
    if(s[cur]=='U')dfs(nx,ny+1,cur+1);
    if(s[cur]=='D')dfs(nx,ny-1,cur+1);
}
int main(){
    int T;
    SI(T);
    while(T--){
        scanf("%d%d%d",&x,&y,&t);
        scanf("%s",s+1);
        ans=INF;
        dfs(0,0,1);
        if(ans==INF)puts("-1");
        else printf("%d
",ans);
    }
    return 0;
} 
原文地址:https://www.cnblogs.com/handsomecui/p/5244662.html