B1021 Deepest Root (强连通+DFS)

B1021 Deepest Root (25分)

//哇,这题炸的好惨~~
20882701-21d1d874a51e21b8.png

1.题目理解问题,不用考虑是否会有个环,保证了它是个强连通图,且是棵树。
2.看到要算几个连通图,直接打完并查集,打完后发现,还是要dfs遍历一遍,没理解并查集的本质是啥???
3.并查集打完磕磕绊绊21分,两个点测试点1和测试点3(写在下面了)。


20882701-12c754f8e949cbcb.png

第一次递归找左侧最长,取左侧一点,往右边递归,两次找到的并集。
//注意1的情况,1就是1,输出时,不是1 1也不是没有输出!!!

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <math.h>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <stack>
#define lowbit(i)((i)&(-i))
using namespace std;
typedef long long ll;
const int MAX=1e4+10;
const int INF=0x3f3f3f3f;
const int MOD=1000000007;
const int SQR=633;
int father[MAX],book[MAX];
vector<int>G[MAX];
int n,maxlevel=0;
vector<int>temppath;
set<int>st;
void dfs(int node,int level)
{
    if(maxlevel<level)
    {
        maxlevel=level;
        temppath.clear();
        temppath.push_back(node);
    }
    else if(maxlevel==level)
    {
        temppath.push_back(node);
    }
    book[G[node][i]]=1;
    for(int i=0;i<G[node].size();i++)
    {
        if(book[G[node][i]]==0)
        {
            //book置为1,测试点3,我脑瘫了
            dfs(G[node][i],level+1);
        }
    }
}
int main()
{
    int num=0,s1=0;
    memset(book,0,sizeof(book));
    scanf("%d",&n);
    for(int i=1;i<MAX;i++)
        father[i]=i;
    for(int i=1;i<=n-1;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        G[x].push_back(y);
        G[y].push_back(x);
    }
    for(int i=1;i<=n;i++)
    {
        if(book[i]==0)
        {
            dfs(i,1);
          if(temppath.size()!=0)
            s1=temppath[0];
          for(int j=0;j<temppath.size();j++)
            st.insert(temppath[j]);
            num++;
        }
    }
    if(num>=2)
    {
         printf("Error: %d components\n",num);
    }
    else
    {
         temppath.clear();
         memset(book,0,sizeof(book));
         dfs(s1,1);
         for(int i=0;i<temppath.size();i++)
         {
             st.insert(temppath[i]);
         }
         for(set<int>::iterator it=st.begin();it!=st.end();it++)
            cout<<*it<<endl;
    }
   return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值