洛谷 P1135奇怪的电梯
代码
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
private static int[][] direct={{0,1},{1,0},{-1,0},{0,-1}};
private static AWriter writer = new AWriter(System.out);
private static AReader reader = new AReader(System.in);
private static int n;
private static double INFINITY=Double.POSITIVE_INFINITY;
private static int a;
private static int b;
private static int s[];
private static int[] m;
public static void main(String[] args) throws IOException {
n=reader.nextInt();
a=reader.nextInt()-1;
b=reader.nextInt()-1;
m=new int[n];
s=new int[n];
for(int i=0;i<n;i++) {
s[i] = reader.nextInt();
m[i]=-1;
}
dfs(a,0);
writer.println(m[b]);
writer.close();
reader.close();
}
private static void dfs(int now,int loyer){
if(m[now]!=-1) {
if(loyer<m[now])
m[now]=loyer;
else
return;
}else {
m[now]=loyer;
}
if(now-s[now]>=0)
dfs(now-s[now],loyer+1);
if(now+s[now]<n)
dfs(now+s[now],loyer+1);
}
}
class AReader implements Closeable {
private BufferedReader reader;
private StringTokenizer tokenizer;
public AReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
tokenizer = new StringTokenizer("");
}
private String innerNextLine() {
try {
return reader.readLine();
} catch (IOException ex) {
return null;
}
}
public boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String nextLine = innerNextLine();
if (nextLine == null) {
return false;
}
tokenizer = new StringTokenizer(nextLine);
}
return true;
}
public String nextLine() {
tokenizer = new StringTokenizer("");
return innerNextLine();
}
public String next() {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.valueOf(next());
}
public long nextLong() {
return Long.valueOf(next());
}
public double nextDouble() {
return Double.valueOf(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
@Override
public void close() throws IOException {
reader.close();
}
}
// Fast writer for ACM By Azure99
class AWriter implements Closeable {
private BufferedWriter writer;
public AWriter(OutputStream outputStream) {
writer = new BufferedWriter(new OutputStreamWriter(outputStream));
}
public void print(Object object) throws IOException {
writer.write(object.toString());
}
public void println(Object object) throws IOException {
writer.write(object.toString());
writer.write("\n");
}
@Override
public void close() throws IOException {
writer.close();
}
}
思路
记忆化搜索。
将当前最短路径放入*s[]*数组,然后遍历,如果不是达到的最短距离则停止