A - Robot Balance
计算B要加多少才大于A
public static void solve() throws IOException {int a = nextInt(), b = nextInt();out.println(Math.max(0, a - b));}
B - Robot Weight
用一个Bool数组记录一下连接情况即可。
public static void solve() throws IOException {int X = nextInt(), n = nextInt();ArrayList<Integer> w = new ArrayList<>(n);for(int i = 0; i < n; i++){w.add(nextInt());}ArrayList<Boolean> st = new ArrayList<>(Collections.nCopies(n, false));int Q = nextInt();while(Q-- > 0){int p = nextInt();p--;if(st.get(p))X -= w.get(p);else X += w.get(p);st.set(p, !st.get(p));out.println(X);}}
C - Robot Factory
贪心的将最轻的K个头和最重和K个身体匹配
public static void solve() throws IOException {int n = nextInt(), m = nextInt(), k = nextInt();ArrayList<Integer> H = new ArrayList<>();ArrayList<Integer> B = new ArrayList<>();for(int i = 0; i < n; i++){H.add(nextInt());}for(int i = 0; i < m; i++){B.add(nextInt());}Collections.sort(H);Collections.sort(B);for(int i = 0; i < k ;i++){if(H.get(i) > B.get(m - k + i)){out.println("No");return;}}out.println("Yes");}
D - Robot Customize
使用f[x]来表示头部为X重量时,最大的开心值。可以发现就是一个01背包。
public static void solve() throws IOException {int n = nextInt();int MAX_TOTAL_WEIGHT = 500 * 500;long[] dp = new long[MAX_TOTAL_WEIGHT + 10];Arrays.fill(dp, -1);dp[0] = 0;int totalWeight = 0;for (int i = 0; i < n; i++) {int w = nextInt();int h = nextInt();int b = nextInt();totalWeight += w;for (int j = totalWeight; j >= 0; j--) {long happinessFromBody = -1;if (dp[j] != -1) {happinessFromBody = dp[j] + b;}long happinessFromHead = -1;if (j >= w && dp[j - w] != -1) {happinessFromHead = dp[j - w] + h;}dp[j] = Math.max(happinessFromBody, happinessFromHead);}}long maxHappiness = 0;for (int j = 0; j * 2 <= totalWeight; j++) {maxHappiness = Math.max(maxHappiness, dp[j]);}out.println(maxHappiness);}
E - Reflection on Grid
其实是一个01边权的图论问题,我们用f[x][y][dir]来表示在(x, y)这个点保持dir方向的最小代价(即节点类型变化次数)
static int[] dx = {1, 0, -1, 0};static int[] dy = {0, 1, 0, -1};public static void solve() throws IOException {int n = nextInt(), m = nextInt();String[] g = new String[n];for(int i = 0; i < n; i++){g[i] = next();}HashMap<Character, Integer> mp = new HashMap<Character, Integer>();mp.put('A', 0);mp.put('B', 1);mp.put('C', 3);int[][][] f = new int[n][m][4];for(int i = 0; i < n; i++)for(int j = 0; j < m; j++)Arrays.fill(f[i][j], 0x3f3f3f3f);// 使用Deque做0-1BFSArrayDeque<int[]> dq = new ArrayDeque<>();dq.addFirst(new int[]{0, -1, 1, 0});while(!dq.isEmpty()){int[] t = dq.pollFirst();int x = t[0], y = t[1], dir = t[2], c = t[3];int a = x + dx[dir], b = y + dy[dir];for(int ndir = 0; ndir < 4; ndir++){if((dir ^ ndir) == 2) continue;if(a < 0 || a >= n || b < 0 || b >= m)continue;// Java怎么这么麻烦...int cost = ((dir ^ ndir) == mp.get(g[a].charAt(b))) ? 0 : 1;if(c + cost < f[a][b][ndir]){f[a][b][ndir] = c + cost;if(cost == 0) dq.addFirst(new int[]{a, b, ndir, f[a][b][ndir]});else dq.addLast(new int[]{a, b, ndir, f[a][b][ndir]});}}}out.println(f[n - 1][m - 1][1]);}