题目链接: 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;
}