#社招内推#百度!欢迎内推人在牛客社招广场发布内推信息:https://www.nowcoder.com/fulltime/center ------------------ 关注@牛客社招助手 ,第一时间获取社招内推信息~
点赞 评论

相关推荐

package xhsimport ("fmt""math")func max(a, b int) int {if a > b {return a}return b}func dfs(node int, parent int, colors []rune, adjList map[int][]int, blackCount []int) int {count := 0if colors[node-1] == 'B' {count = 1}for _, child := range adjList[node] {if child == parent {continue}count += dfs(child, node, colors, adjList, blackCount)}blackCount[node] = countreturn count}func findMaxBlackNodes(n int, colors string, edges [][]int) int {adjList := make(map[int][]int)blackCount := make([]int, n+1)// 建立邻接表for _, edge := range edges {u, v := edge[0], edge[1]adjList[u] = append(adjList[u], v)adjList[v] = append(adjList[v], u)}// 颜色转换为字符数组colorRunes := []rune(colors)// 从根节点开始进行DFS,计算黑色节点数量dfs(1, -1, colorRunes, adjList, blackCount)// 找到删除一个红色节点后的最大黑色节点数maxBlack := math.MinInt32for i := 1; i <= n; i++ {for _, node := range adjList[i] {if colorRunes[node-1] == 'R' {maxBlack = max(maxBlack, blackCount[i]-blackCount[node])}}}return maxBlack}func XHS9_1_3main() {n := 10colors := "RRBBBBBBBB"edges := [][]int{{1, 2},{1, 3},{1, 4},{1, 5},{1, 7},{2, 8},{4, 6},{4, 10},{6, 9},}result := findMaxBlackNodes(n, colors, edges)fmt.Println(result) // 输出 7}
查看2道真题和解析 投递小红书等公司10个岗位
点赞 评论 收藏
分享
牛客网
牛客企业服务