280

This also can be solved using bfs or dfs.

#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;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *