Sanath12345

Untitled

Jun 4th, 2021
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int n,m,k;
  4. int visited[27];
  5. int start=0;
  6. queue<int> Q;
  7. int BFS(int G[][27],int x){
  8. Q.push(start);
  9. Q.push(-1);
  10. int l=0;
  11. while(!Q.empty()){
  12. int z=Q.front();
  13. Q.pop();
  14. if(z==-1){
  15. l++;
  16. if(!Q.empty()){
  17. z=Q.front();
  18. Q.pop();
  19. Q.push(-1);
  20. }
  21. else break;
  22. }
  23. if(visited[z]==1) continue;
  24. visited[z]=1;
  25. for(int i=0;i<26;i++){
  26. if(G[z][i]==1){
  27. char p=z+'a';
  28. char q=i+'a';
  29. cout<<p<<"->"<<q<<endl;
  30. if(q==x){
  31. return 1;
  32. }
  33. Q.push(i);
  34. }
  35. }
  36. if(l==k){
  37. break;
  38. }
  39. }
  40. return -1;
  41. }
  42. int found=0;
  43. void DFS(vector<int> rem,int v,int G[][27],char x){
  44. char c=v+'a';
  45. visited[v]=1;
  46. for(int i=0;i<26;i++){
  47. if(found==0 and G[v][i]==1 and visited[i]==0){
  48. char z=i+'a';
  49. cout<<c<<"->"<<z<<endl;
  50. if(z==x){
  51. found=1;
  52. return ;
  53. }
  54. DFS(rem,i,G,x);
  55. }
  56. }
  57. }
  58. int SEARCH(int G[][27],int x){
  59. int a=BFS(G,x);
  60. if(a==1) return 1;
  61. vector<int> rem;
  62. while(!Q.empty()){
  63. int z=Q.front();
  64. if(z!=-1 and visited[z]==0) rem.push_back(z);
  65. Q.pop();
  66. }
  67. sort(rem.begin(),rem.end());
  68. found=0;
  69. for(int i=0;i<rem.size();i++){
  70. if(visited[rem[i]]==0 and found==0){
  71. DFS(rem,rem[i],G,x);
  72. }
  73. }
  74. if(found==1) return 1;
  75. for(int i=0;i<n;i++){
  76. if(visited[i]==0){
  77. start=i;
  78. int p=SEARCH(G,x);
  79. if(p==1) return 1;
  80. }
  81. }
  82. return -1;
  83. }
  84. int main(){
  85. cin>>n>>m>>k;
  86. int G[27][27];
  87. memset(G,0,sizeof(G));
  88. for(int i=0;i<m;i++){
  89. char x,y;
  90. cin>>x>>y;
  91. G[x-'a'][y-'a']=1;
  92. }
  93. char x;
  94. cin>>x;
  95. memset(visited,0,sizeof(visited));
  96. cout<<SEARCH(G,x)<<endl;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment