阿里笔试AK
第一题
水塔问题公式
在(n+1)/2上防水塔
import java.util.Arrays; import java.util.Scanner; /** * Package: PACKAGE_NAME * Created by OriKey on 2020/8/10. * --- 平凡才是唯一的答案 --- */ public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long[]arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextLong(); } Arrays.sort(arr); long sum = 0; for (int i = 0; i < n; i++) { sum+=Math.abs(arr[(n+1)/2-1]-arr[i]); } System.out.println(sum); } // public static void main(String[] args) { // Scanner in = new Scanner(System.in); // // }s
第二题
求深度....肯定是比较浅的那个先赢。
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 10; int n, m; vector<int> v[MAXN]; int dep[MAXN]; void dfs(int x) { for (auto y : v[x]) { dep[y] = dep[x] + 1; dfs(y); } } int main() { scanf("%d%d", &n, &m); for (int i = 2; i <= n; i++) { int x; scanf("%d", &x); v[x].push_back(i); } dfs(1); for (int i = 1; i <= m; i++) { int x, y; scanf("%d%d", &x, &y); if (dep[x] <= dep[y]) printf("A\n"); else printf("B\n"); } }