880. 数字对生成树

题目链接: https://www.acwing.com/problem/content/description/882/
本身不是一个难题,就是对c++很多骚操作不是很了解,,还有就是,,又是不长记性的一天,size大小不对第一时间就应该想到我又把for循环的花括号范围弄错了,,,我竟然忘了,,然后debug了半天,,,,,

#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
using namespace std;

//广搜+时间戳排序输出
//判断有无环,直接在宽搜距离的时候顺便看看这个点是不是两次遍历即可(即 dist数组是不是已经有了他了)

//判读是否是树
//1 \有一个根节点
//2\可以从根节点遍历到其他所有点
//3、每个点只遍历一次

map<int,vector<int> >h; //存储整个图,h[5]存储以5为七点的的所有边
map<int,int>timestamp,dist; //dist表示每个点到根节点的距离
map<int,bool>has_father;
map<pair<int,int>,bool> edges;

vector<int> bfs(int root){
    queue<int> q;
    q.push(root);
    dist[root] = 0;
    vector<int> nodes;

    while(q.size()){
        auto t = q.front();
        q.pop();
        nodes.push_back(t);

        for(auto ver:h[t]){
            if(dist.count(ver)) return vector<int>();

            dist[ver] = dist[t]+1;
            q.push(ver);
        }
    }




    vector<vector<int>> ans;
    for(auto ver:nodes){
        ans.push_back({dist[ver],timestamp[ver],ver}); //花括号里面是一个数组

    }

        sort(ans.begin(),ans.end());

        nodes.clear();
        for(auto t:ans) nodes.push_back(t[2]);

        return nodes;

}
int main(){
  int tm=0;
    int n;
    cin>>n;
    while(n--){
        int a,b;
        scanf("%d,%d",&a,&b);
        if(edges[{a,b}]) continue;
        else edges[{a,b}] = true;

        if(timestamp.count(a) ==0) timestamp[a] = tm++;
        if(timestamp.count(b) ==0) timestamp[b]= tm++;
        has_father[b] = true;

        h[a].push_back(b);
    }
    int root= -1;
    for(auto x:timestamp){
        int p = x.first;
        if(!has_father[p]){
            root =  p;
            break;
        }
    }
    if(!root) puts("Not a tree");
    else{
        auto res  = bfs(root);

        if(res.size()<timestamp.size()) puts("Not a tree"); //不能从根节点遍历到其它所有节点
        else{
            cout<< res[0];
            for(int i= 1;i<res.size();i++){
                cout<< ','<<res[i];
            }
            cout<<endl;
        }
    }
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值