9.15蚂蚁笔试23题
第二题,只能过90%,知道哪里有问题的大佬可以解答一下。。磕一个
import java.util.*;
public class Main {
static long res = 0;
static ArrayList<Integer>[] tree;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
tree = new ArrayList[n + 1];
for (int i = 0; i < n - 1; ++i) {
int u = sc.nextInt();
int v = sc.nextInt();
if (u > v) {
int t = u;
u = v;
v =t;
}
if (tree[u] == null) {
tree[u] = new ArrayList<>();
}
tree[u].add(v);
}
dfs(1, 0L);
System.out.println(res);
}
static void dfs(int root, long add) {
long count = root - 1 - add;
res += count;
if (tree[root] != null) {
for (int i = 0; i < tree[root].size(); ++i) {
dfs(tree[root].get(i), add + count);
}
}
}
} 第三题 100%
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
Map<Integer, Integer> hm = new HashMap<>();
long res = 0;
int cur = 0;
hm.put(0, 1);
for (char c : str.toCharArray()) {
cur ^= 1 << (c - 'a');
for (int i = 0; i < 26; ++i) {
res += hm.getOrDefault(cur ^ (1 << i), 0);
}
hm.put(cur, hm.getOrDefault(cur, 0) + 1);
}
System.out.println(res);
}
}
查看3道真题和解析
