6 条题解
-
1
题目给出不会有重边和环,正向考虑相当于一条路有多条分叉,一个出口只会对应一个入口,因此倒着考虑比较合适,自然而然想到递归的解法 思路: 建立一个哈希表来存储出口所对应的入口,如实例给的1对应0,只需记录hash[1]=0;存入后递归输出相应的值即可。 `
代码如下
using namespace std; int n,q,x,y; int target[1005];//定义出口数组 int main(){ ios_base::sync_with_stdio(0);//输入量较大,关闭同步流,或者是用printf and scanf cin.tie(0);cout.tie(0); cin>>n>>q; unordered_map<int,int>hash;//建立哈希表 for(int i=0;i< n;i++){ cin>>x>>y; hash[y]=x;//对应入口存入hash表 } //递归解决问题 auto dfs=[&](auto&&dfs,int x)->void{ //x==0输出并返回 if(!x){ cout<<x<<' '; return; } dfs(dfs,hash[x]);//递归调用后输出 cout<<x<<' '; return; }; for(int i=0;i<q;i++)cin>>target[i]; for(int i=0;i<q;i++){ dfs(dfs,target[i]);//调用递归表达式 cout<<'\n'; } return 0; }
时间复杂度:O(qn); 空间复杂度:O(qn); //希望我的题解对你有帮助
信息
- ID
- 964
- 时间
- 2000ms
- 内存
- 256MiB
- 难度
- 6
- 标签
- 递交数
- 350
- 已通过
- 106
- 上传者