This also can be solvedĀ using bfs or dfs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
#include <iostream> #include <string.h> #include <vector> #define INF 1000000000 using namespace std; int gr[105][105]; int n,from,to; int tt; vector<int> vb; void init() { for(int i=0;i<105;i++) for(int j=0;j<105;j++) { gr[i][j]=INF; } } void floyd() { for(int k=1;k<=n;k++) { for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(gr[i][j]>gr[i][k]+gr[k][j]) gr[i][j] = gr[i][k]+gr[k][j]; } } } } int main() { int ch; while(cin>>n) { if(n==0) break; init(); while(cin>>from) { if(from==0) break; while(cin>>to) { if(to==0) break; gr[from][to]=1; } } floyd(); cin>>tt; while(tt--) { cin>>ch; vb.clear(); for(int x=1;x<=n;x++) if(gr[ch][x]==INF) vb.push_back(x); cout<<vb.size(); for(int x=0;x<vb.size();x++) cout<<" "<<vb[x]; cout<<"\n"; } } return 0; } |