奇安信算法笔试

1。共同祖先(二叉树可以用数组表示,只要判断俩个节点的索引是否能够相等就能找到共同祖先)
2。蠕虫感染(傻子暴力做法)
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNextLine()) {
int n = Integer.parseInt(in.nextLine());
int[][] m = new int[n][n];
int[] node = new int[n];
Queue<Integer> q = new LinkedList<>();

for(int i=0;i<n;i++) {
String[] str = in.nextLine().split(" ");
for(int j=0;j<n;j++) {
m[i][j] = Integer.parseInt(str[j]);

}
}
String[] s = in.nextLine().split(" ");
for(int i=0;i<s.length;i++) {
q.add(Integer.parseInt(s[i]));
node[Integer.parseInt(s[i])] =1;

}

int M = bfs(m,q);
int result = -1;
for(int i=0;i<node.length;i++) {
if(node[i]==1) {
q.remove(i);
int  mm = bfs(m,q);
if(M>mm) {
M=mm;
result = i;
}
q.add(i);
}
}
System.out.println(result);

}



}
public static int bfs(int[][] m, Queue<Integer> q) {
int count=0;
Set<Integer> set = new TreeSet<>();
while(!q.isEmpty()) {
int top = q.poll();
count++;
for(int i=0;i<m.length;i++) {
if(m[top][i]==1&&!set.contains(i)) {
q.add(i);
set.add(i);
}
}

}

return count;
}
}

#笔试题目##奇安信##算法工程师#
全部评论
from collections import defaultdict, Counter from queue import deque import sys line = sys.stdin.readline() lines = sys.stdin.readlines() l = [] for  i in range(len(lines)-1):     l.append(list(map(int, lines[i].strip().split()))) init = list(map(int, lines[-1].strip().split())) from_which = defaultdict(set) q = deque() visited = set() for i in init:     q.append(i)     visited.add(i)     from_which[i].add(i) while q:     cur = q.popleft()     for i, v in enumerate(l[cur]):         if v == 1 and i != cur:             from_which[i] = from_which[i].union(from_which[cur])             if i not in visited:                 q.append(i)                 visited.add(i) result = [] for k in from_which:     if len(from_which[k]) == 1:         result.append(list(from_which[k])[0]) # init = list(filter(lambda x: len(from_which[x]) == 1, init)) c = Counter(result) r = 0 m = 0 for i in init:     if len(from_which[i]) == 1 and c[i] > m:         r = i         m = c[i] print(r) 温柔做法,a了63,我哭了
点赞 回复
分享
发布于 2019-09-09 20:46

相关推荐

1 3 评论
分享
牛客网
牛客企业服务