【HDOJ】3660 Alice and Bob's Trip
就是一个基本的dfs。可关键问题是c/c++/g++光输入就超时了。还是写java过的,毕竟时限4s。都放弃希望了,没想到还真过了。
1 import java.lang.*; 2 import java.io.*; 3 import java.util.*; 4 5 6 public class Main { 7 8 public static void main(String[] args) throws java.lang.Exception { 9 InputStream inputStream = System.in; 10 OutputStream outputStream = System.out; 11 InputReader in = new InputReader(inputStream); 12 PrintWriter out = new PrintWriter(outputStream); 13 TaskA solver = new TaskA(); 14 solver.solve(in, out); 15 out.close(); 16 } 17 } 18 19 class TaskA { 20 public final static int maxv = (int)(5e5+5); 21 public final static int INF = 0x3f3f3f3f; 22 int[] V = new int[maxv]; 23 int[] W = new int[maxv]; 24 int[] nxt = new int[maxv]; 25 int[] head = new int[maxv]; 26 int m, n, L, R; 27 28 void init() { 29 m = 0; 30 Arrays.fill(head, -1); 31 } 32 33 void addEdge(int u, int v, int w) { 34 V[m] = v; 35 W[m] = w; 36 nxt[m] = head[u]; 37 head[u] = m++; 38 } 39 40 public void solve(InputReader in, PrintWriter out) { 41 int i; 42 int u, v, w; 43 int ans; 44 45 while (true) { 46 try { 47 n = in.nextInt(); 48 } catch (RuntimeException e) { 49 break; 50 } 51 L = in.nextInt(); 52 R = in.nextInt(); 53 init(); 54 for (i=1; i<n; ++i) { 55 u = in.nextInt(); 56 v = in.nextInt(); 57 w = in.nextInt(); 58 addEdge(u, v, w); 59 } 60 ans = dfs(0, 0, 0); 61 if (ans == INF) 62 out.println("Oh, my god!"); 63 else 64 out.println(ans); 65 } 66 } 67 68 private int dfs(int u, int len, int now) { 69 int ans = -1; 70 71 if (head[u] == -1) 72 return 0; 73 int i, v, w; 74 75 for (i=head[u]; i!=-1; i=nxt[i]) { 76 v = V[i]; 77 w = W[i]; 78 int tmp = dfs(v, len+w, now^1) + w; 79 if (tmp == INF) 80 continue; 81 if (tmp>=L-len && tmp<=R-len) { 82 if (now == 0) { 83 if (ans==-1 || tmp>ans) 84 ans = tmp; 85 } else { 86 if (ans==-1 || tmp<ans) 87 ans = tmp; 88 } 89 } 90 } 91 92 if (ans == -1) 93 return INF; 94 return ans; 95 } 96 } 97 98 class InputReader { 99 public BufferedReader reader; 100 public StringTokenizer tokenizer; 101 102 public InputReader(InputStream stream) { 103 reader = new BufferedReader(new InputStreamReader(stream), 32768); 104 tokenizer = null; 105 } 106 107 public String next() { 108 while (tokenizer==null || !tokenizer.hasMoreTokens()) { 109 try { 110 tokenizer = new StringTokenizer(reader.readLine()); 111 } catch (IOException e) { 112 throw new RuntimeException(e); 113 } 114 } 115 return tokenizer.nextToken(); 116 } 117 118 public int nextInt() { 119 return Integer.parseInt(next()); 120 } 121 }