输入格式:
输入首先在一行中给出正整数 N(<105),是门的数量。最后 N 行,第 i 行(1≤i≤N)按以下格式描述编号为 i 的那扇门背后能通向的门:
K D[1] D[2] ... D[K]
其中 K
是通道的数量,其后是每扇门的编号。
输出格式:
在一行中输出距离入口最远的那扇门的编号。题目保证这样的结果是唯一的。
输入样例:
13
3 2 3 4
2 5 6
1 7
1 8
1 9
0
2 11 10
1 13
0
0
1 12
0
0
输出样例:
12
题解:
1.邻接表法
#include<iostream>
#include<queue>
using namespace std;
const int maxn=1e5+5;
int n,st,vis[maxn]= {0};
vector<int>edge[maxn];//邻接表
int main() {
queue<int >q;
cin>>n;
int n1=n;
for(int g=1; g<=n; g++) {
int k;
cin>>k;
for(int i=1; i<=k; i++) {
int t;
cin>>t;
edge[g].push_back(t);
vis[t]=1;
}
}
for(int i=1; i<=n; i++) {
if(!vis[i]) {//找到入口的编号
st=i;
break;
}
}
q.push(st);//放进起点编号
int i1;
while(!q.empty()) {
i1=q.front();
q.pop();
for(int j=0; j<edge[i1].size(); j++) {
q.push(edge[i1][j]);
}
}
cout<<i1;
return 0;
}
2.邻接表改进(用几个数组表示邻接表减少空间)
#include<bits/stdc++.h>
using namespace std;
#include<queue>
queue<int>q;
const int maxn=1e5+5;
int n,st,idx=0,vis[maxn]= {0};
int e[maxn],ne[maxn],h[maxn];//用这些数组代替邻接表
void add(int a,int b) {
e[idx]=b,ne[idx]=h[a],h[a]=idx++;//ne数组和h数组连接一条邻接的线
}
int main() {
cin>>n;
int n1=n;
memset(h,-1,sizeof(h));
for(int g=1; g<=n; g++) {
int k;
cin>>k;
for(int i=1; i<=k; i++) {
int t;
cin>>t;
add(g,t);
vis[t]=1;
}
}
for(int i=1; i<=n; i++) {
if(!vis[i]) {
st=i;
break;
}
}
q.push(st);
int i1;
while(!q.empty()) {
i1=q.front();
q.pop();
for(int j=h[i1]; j!=-1; j=ne[j]) {//往前回溯遍历一条邻接线
q.push(j);
}
}
cout<<i1;
return 0;
}