百度3.28笔试题原题A了多少

投票
#笔试复盘##百度笔试#原题啊,兄弟么,第三题就是A不了,超时,哪位好兄弟帮忙看看
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        String color=sc.nextLine();
        List<List<Integer>> edge=new ArrayList<>();
        edge.add(new ArrayList<>());
        while(sc.hasNextLine()){
            int a=sc.nextInt();
            int b=sc.nextInt();
            sc.nextLine();
            while(a>=edge.size()) edge.add(new ArrayList<>());
            while(b>=edge.size()) edge.add(new ArrayList<>());
            if(a==b) continue;
            edge.get(a).add(b);
            edge.get(b).add(a);
        }
        allBlock=new int[n+1];
        dfs1(1,0,edge,color);
        dfs2(1,0,edge,color);
        System.out.println(res);
    }
    static int res=0;
    public static void dfs2(int cur,int parent,List<List<Integer>> edge,String color){
        for(int i=0;i<edge.get(cur).size();i++){
            int next=edge.get(cur).get(i);
            if(next==parent) continue;
            dfs2(next,cur,edge,color);
            if(color.charAt(cur-1)==color.charAt(next-1)){
                res+=Math.abs(allBlock[next]-(allBlock[1]-allBlock[next]+1));
            }else{
                res+=Math.abs(allBlock[next]-(allBlock[1]-allBlock[next]));
            }
        }
    }
    static int allBlock[];
    public static int dfs1(int cur,int parent,List<List<Integer>> edge,String color){
        int curblock=1;
        for(int i=0;i<edge.get(cur).size();i++){
            int next=edge.get(cur).get(i);
            if(next==parent) continue;
            allBlock[cur]+=dfs1(next,cur,edge,color);
            if(color.charAt(cur-1)==color.charAt(next-1)) allBlock[cur]--;
        }
        return allBlock[cur];
    }
}
全部评论
原题的嘛兄弟你是哪个卷 我咋感觉题不一样
点赞
送花
回复
分享
发布于 2023-03-28 21:09 辽宁
怎么感觉你这第三题和我的不一样
点赞
送花
回复
分享
发布于 2023-03-28 21:10 湖北
秋招专场
校招火热招聘中
官网直投
我第三题也一直超时... 而且每次提交还ac不一样 btw怎么没有2-3这个选项。。
点赞
送花
回复
分享
发布于 2023-03-28 21:16 广东

相关推荐

头像
不愿透露姓名的神秘牛友
05-27 11:41
已编辑
点赞 评论 收藏
转发
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务