Just CS rookie practice on DFS\BFS. But details should be taken care of:
1. Ruby implementation got TLE so I switched to C++
2. There's one space after each output node, including the last one. But SPOJ doesn't clarify it clearly.
// #include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <algorithm>
using namespace std; typedef map<int, vector<int> > Graph; void bfs(Graph &g, int key)
{
vector<int> visited; visited.reserve(g.size());
for(unsigned ic = ; ic < g.size(); ic ++)
{
visited[ic] = ;
} queue<int> fifo;
fifo.push(key);
while(!fifo.empty())
{ int cKey = fifo.front();
fifo.pop(); if(visited[cKey - ] == )
{
cout << cKey <<" "; vector<int> &ajVec = g[cKey];
for(unsigned i = ; i < ajVec.size(); i ++)
{
fifo.push(ajVec[i]);
}
visited[cKey - ] = ;
}
} cout << endl;
} vector<int> dfs_rec;
void initDfsRec(Graph &g)
{
dfs_rec.clear();
unsigned gSize = g.size();
dfs_rec.reserve(gSize);
for(unsigned ic = ; ic < gSize; ic ++)
{
dfs_rec[ic] = ;
}
} void dfs(Graph &g, int key)
{
cout << key << " ";
dfs_rec[key - ] = ;
vector<int> &ajVec = g[key];
for(unsigned i = ; i < ajVec.size(); i ++)
{
if(dfs_rec[ajVec[i] - ] == )
{
dfs(g, ajVec[i]);
}
}
} int main()
{ int runcnt = ;
cin >> runcnt;
for(int i = ; i < runcnt; i ++)
{
Graph g; int nvert = ; cin >> nvert;
for(int n = ; n < nvert; n ++)
{
int vid = ; cin >> vid;
int cnt = ; cin >> cnt;
vector<int> ajVec;
for(int k = ; k < cnt; k ++)
{
int aj = ; cin >> aj;
ajVec.push_back(aj);
} g.insert(Graph::value_type(vid, ajVec));
} //
cout << "graph " << i + << endl; int ikey = , iMode = ;
cin >> ikey >> iMode;
while(!(ikey == && iMode == ))
{
if(iMode == )
{
initDfsRec(g);
dfs(g, ikey);
cout <<endl;
}
else if(iMode == )
{
bfs(g, ikey);
}
cin >> ikey >>iMode;
}
} return ;
}