fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define sp " "
  5. #define el '\n'
  6. #define ll long
  7. int n;
  8. vector<int> p;
  9. vector<int> d;
  10. vector<int>vis;
  11. map<int,int>mp;
  12. map<int,int> con;
  13. ll ans = 0;
  14. set<int>s;
  15. void dfs(int i){
  16. //cout << i << el;
  17. if(!vis[i]){
  18. vis[i] = 1;
  19. int k = p[i];
  20. p[i] = mp[k];
  21. s.erase(k);
  22. s.insert(p[i]);
  23. if(s.size() == n) {
  24. ans++;
  25. //cout << ans << sp << i << el;
  26. return;
  27. }
  28. else{
  29. ans++;
  30. dfs(con[p[i]]);
  31. }
  32. }
  33. }
  34. void Solution()
  35. {
  36. cin >> n;
  37. p = vector<int> (n+1);
  38. d = vector<int> (n+1);
  39. vis = vector<int> (n+1,0);
  40. for(int i = 1; i <= n; i++){
  41. cin >> p[i];
  42. s.insert(p[i]);
  43. mp[p[i]] = i;
  44. }
  45. for(int i = 1; i <= n; i++){
  46. cin >> d[i];
  47. con[p[i]] = d[i];
  48. }
  49. for(int i = 1; i <= n; i++){
  50. if(!vis[i]) dfs(d[i]);
  51. cout << ans << sp;
  52. }
  53. cout << el;
  54.  
  55.  
  56.  
  57. }
  58. int main()
  59. {
  60. ios::sync_with_stdio(0);
  61. cin.tie(0); cout.tie(0);
  62. // int t;
  63. // cin >> t;
  64. // for(int tc = 1; tc <= t; tc++)
  65. Solution();
  66. return 0;
  67. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout