百度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 广东

相关推荐

黑皮白袜臭脚体育生:简历统一按使用了什么技术实现了什么功能解决了什么问题或提升了什么性能指标来写会更好
点赞 评论 收藏
分享
乐观的打工人前程似锦:怎么说呢🤔️,学历够,专业技能看起来也有那么回事,就是项目会不会差点?dji更喜欢较为复杂的工程落地的项目吧?如果有一些title的项目就更好了。有实习也是加分项,搞过神经网络应该也是加分项。进面应该可以,还是要看技术过硬
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务