第一题
package ccf201812; import java.util.Scanner; public class p1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int r = sc.nextInt(); int y = sc.nextInt(); int g = sc.nextInt(); int n = sc.nextInt(); int[] k = new int[n]; int[] t = new int[n]; for (int i = 0; i < n; i++) { k[i] = sc.nextInt(); t[i] = sc.nextInt(); } int res = 0; for (int i = 0; i < n; i++) { if (k[i] == 0 || k[i] == 1) { res += t[i]; } else if (k[i] == 2) { res += t[i] + r; } else { res += 0; } } System.out.println(res); } }
第二题(用int值会溢出报错,所以要用long)
package ccf201812; import java.util.Scanner; public class p2s { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long r = sc.nextInt(); long y = sc.nextInt(); long g = sc.nextInt(); long n = sc.nextInt(); long[] k = new long[(int) n]; long[] t = new long[(int) n]; for (int i = 0; i < n; i++) { k[i] = sc.nextInt(); t[i] = sc.nextInt(); } long res = 0; for (int i = 0; i < n; i++) { if (k[i] == 0) { res += t[i]; } else { long[] kt = getRYG(r, y, g, k[i], t[i], res); if (kt[0] == 1) {//此时为红灯 res += kt[1]; } else if (kt[0] == 2) {//此时为黄灯 res += kt[1] + r; } else {//此时为绿灯 res += 0; } } } System.out.println(res); } public static long[] getRYG(long r, long y, long g, long k, long t, long time) { long[] kt = new long[2]; long s = r + y + g; long temp = time % s; if (k == 1) { //出发时是红灯 if (temp - t < 0) { kt[0] = 1; kt[1] = t - temp; //到达时未变色还是红灯 } else if (temp - t < g) { kt[0] = 3; kt[1] = g - (temp - t); //到达时变为绿灯 } else if (temp - t < g + y) { kt[0] = 2; kt[1] = g + y - (temp - t); //到达时变为黄灯 } else { kt[0] = 1; kt[1] = g + y + r - (temp - t); //到达时由红变绿变黄又变红 } } else if (k == 2) { //出发时是黄灯 if (temp - t < 0) { kt[0] = 2; kt[1] = t - temp; //到达时黄灯未变色 } else if (temp - t < r) { kt[0] = 1; kt[1] = r - (temp - t); //到达时变为红灯 } else if (temp - t < g + r) { kt[0] = 3; kt[1] = g + r - (temp - t); // 到达时变为绿灯 } else { kt[0] = 2; kt[1] = g + y + r - (temp - t); //到达时又变为黄灯 } } else { //出发时是绿灯 if (temp - t < 0) { kt[0] = 3; kt[1] = t - temp; //到达时绿灯未变色 } else if (temp - t < y) { kt[0] = 2; kt[1] = y - (temp - t); //到达时变为黄灯 } else if (temp - t < r + y) { kt[0] = 1; kt[1] = r + y - (temp - t); //到达时变为红灯 } else { kt[0] = 3; kt[1] = g + y + r - (temp - t); //到达时变为绿灯 } } return kt; } }