您的位置:首页 > 编程语言

# 美团点评CodeM编程大赛-题四

2017-06-16 18:09 501 查看

美团点评CodeM编程大赛-题四

题目描述

n 个小区排成一列,编号为从 0 到 n-1 。一开始,美团外卖员在第0号小区,目标为位于第 n-1 个小区的配送站。

给定两个整数数列 a[0]~a[n-1] 和 b[0]~b[n-1] ,在每个小区 i 里你有两种选择:

1) 选择a:向前 a[i] 个小区。

2) 选择b:向前 b[i] 个小区。

把每步的选择写成一个关于字符 ‘a’ 和 ‘b’ 的字符串。求到达小区n-1的方案中,字典序最小的字符串。如果做出某个选择时,你跳出了这n个小区的范围,则这个选择不合法。

• 当没有合法的选择序列时,输出 “No solution!”。

• 当字典序最小的字符串无限长时,输出 “Infinity!”。

• 否则,输出这个选择字符串。

字典序定义如下:串s和串t,如果串 s 字典序比串 t 小,则

• 存在整数 i ≥ -1,使得∀j,0 ≤ j ≤ i,满足s[j] = t[j] 且 s[i+1] < t[i+1]。

• 其中,空字符 < ‘a’ < ‘b’。

输入描述:

输入有 3 行。

第一行输入一个整数 n (1 ≤ n ≤ 10^5)。

第二行输入 n 个整数,分别表示 a[i] 。

第三行输入 n 个整数,分别表示 b[i] 。

−n ≤ a[i], b[i] ≤ n

输出描述:

输出一行字符串表示答案。

输入例子:

7

5 -3 6 5 -5 -1 6

-6 1 4 -2 0 -2 0

输出例子:

abbbb

语言

JAVA JDK1.7

代码

import java.util.*;

/**
* @ClassName:
* @Description:
* @Author: Arthur
* @Date: 2017/6/16 10:03
* @version: V1.0.0.0
*/
public class Main {
static List<String> paths=new ArrayList<String>();
static List<Integer> aPaths=new ArrayList<>();
static List<Integer> bPaths=new ArrayList<>();
static int num=0;
static boolean flag=false;
public static void  main(String[] args){
Scanner sc = new Scanner(System.in);
//小区的数量
num = sc.nextInt();
for (int i = 0; i <num; i++) {
aPaths.add(sc.nextInt());
if (aPaths.get(i)+i<0||aPaths.get(i)+i>=num){
aPaths.set(i,0);
}
}
for (int i = 0; i <num; i++) {
bPaths.add(sc.nextInt());
if (bPaths.get(i)+i<0||bPaths.get(i)+i>=num){
bPaths.set(i,0);
}
}
String goPath="";
deepCount(0,0,goPath,"");
if (paths.size()==0){
System.out.println("No solution!");
}else{
Object[] pathsArr=  paths.toArray();
Arrays.sort(pathsArr);
System.out.println(pathsArr[0]);
}
}
/**
* @Method: deepCount
* @Description:
* @param : a a路径序列
* @param : b b路径序列
* @param : currentIndex 当前位置
* @param : n 小区总数
* @return: void
* @Arhuor: Arthur
* @date: 2017/6/16 10:23
* @Version: 1.0.0.0
*/
public static void deepCount(int lastIndex,int currentIndex,String goPath,String path){
String orgingoPath=goPath;
if (currentIndex==num-1){
paths.add(path);
if (path.substring(path.length()-1).equals("a")){
flag=true;
}
return;
}
//超出界限
if(currentIndex<0||currentIndex>num-1){
return;
}
//选择A路径,不越界,不重复
int aGoIndex=currentIndex+aPaths.get(currentIndex);
if (aGoIndex>0&&aGoIndex<num&&!goPath.contains("a"+(aGoIndex))&&(aPaths.get(aGoIndex)!=0||aGoIndex==num-1)){
goPath=goPath+("a"+aGoIndex);
deepCount(currentIndex,aGoIndex,goPath,path+"a");
}
if (flag)return;
goPath=orgingoPath;
int bGoIndex=currentIndex+bPaths.get(currentIndex);
if (bGoIndex>=0&&bGoIndex<num&&!goPath.contains("b"+(bGoIndex))&&(bPaths.get(bGoIndex)!=0||bGoIndex==num-1)){
goPath=goPath+("b"+bGoIndex);
deepCount
4000
(currentIndex,bGoIndex,goPath,path+"b");
}
}
}


注:已经去除一些无用点的选择,当路径A完成时不考虑路径B。但是还是没通过,这里采用递归方式,时间上花费还是比较多的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: