(自用随笔)PAT A1021(25分)

暴力搜索,测试点3用了1200ms。。。。尴尬。

测试点2比较坑,连通分支数大于2,而我一开始的代码是,一旦连通分支大于1则跳出。。。

用fill函数的时候也犯错了,因为是从1到N编号,我一开始没有+1,导致最后一个vis没有赋值为0。。

 

暴力思路:先把节点1作为根,用一次图的遍历模板,将连通分支数算出来,若大于1则输出Error;若等于1,则把剩下的节点分别作为根,遍历,算出各自的最大深度,最后输出最大深度的节点。

优化的思路请参考其他博客~

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>

using namespace std;

int N;
vector<int> G[10005];
bool vis[10005];
int maxdepth = -1;
int mmdepth = -1;
int component;
int road = 0;
int deep[10005];

void DFS(int x,int root,int depth)
{
    vis[x] = true;
    if(depth>maxdepth)
    {
        maxdepth = depth;
    }
    for(int j = 0;j<G[x].size();j++)
    {
        int v = G[x][j];
        if(!vis[v])
        {
            DFS(v,root,depth+1);
        }
    }
}

void DFSTravel(int root)
{
    for(int i = 1;i<=N;i++)
    {
        if(!vis[i])
        {
            component++;
            DFS(i,root,1);
            deep[root] = maxdepth;
            if(maxdepth>mmdepth)
            {
                mmdepth = maxdepth;
            }
            maxdepth = -1;
        }
    }
}

void DFSTravel2(int root)
{
    if(!vis[root])
    {
        DFS(root,root,1);
        deep[root] = maxdepth;
        if(maxdepth>mmdepth)
        {
            mmdepth = maxdepth;
        }
        maxdepth = -1;
    }
}

int main()
{
    scanf("%d",&N);
    int a,b;
    for(int i = 0;i<N-1;i++)
    {
        scanf("%d %d",&a,&b);
        G[a].push_back(b);
        G[b].push_back(a);
    }

    DFSTravel(1);
    if(component>1)
    {
        printf("Error: %d components",component);
        return 0;
    }
    for(int k = 2;k<=N;k++)
    {
        fill(vis,vis+N+1,false);
        DFSTravel2(k);
    }

    for(int l = 1;l<=N;l++)
    {
        if(deep[l] == mmdepth)
        {
            printf("%d\n",l);
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值