Sunday, July 10, 2016

My first graph problem solved: "10928 - My Dear Neighbours"

[UPDATE (July 27, 2016): I remember that this is not really the first graph problem I solved. It is, rather, the first graph problem on UVA Online Judge that I solved. I was already able to solve a graph problem when I took the free Stanford course named CS106B last 2011. But I already forgot how I solved it.]

I am so excited!!!

I solved my first graph related problem: the UVA Online Judge's problem #10928 "My Dear Neighbours".

This might just be a very simple problem but at least I am able to get started with solving graph problems.

Picture taken from http://uhunt.felix-halim.net/

Here is my solution:
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
int numOfTestCases;
cin >> numOfTestCases;
// foreach test case
for(int n = 0; n < numOfTestCases; n++)
{
int numOfPlaces;
cin >> numOfPlaces;
cin.ignore(100,'\n');
// assign N number of vector<int> to the adjacencyList
vector<vector<int> > adjacencyList(numOfPlaces, vector<int>());
int currentMinimumNumberOfNeighbors = numOfPlaces - 1;
//foreach place
for(int currentPlace = 0; currentPlace < numOfPlaces; currentPlace++)
{
string strNeighbors;
getline(cin, strNeighbors);
stringstream stream(strNeighbors);
int currentNeighbor;
int numOfNeighborsInCurrentPlace = 0;
while(stream >> currentNeighbor)
{
adjacencyList[currentPlace].push_back(currentNeighbor);
numOfNeighborsInCurrentPlace++;
}
// update current minimum number of neighbors
if(numOfNeighborsInCurrentPlace < currentMinimumNumberOfNeighbors)
{
currentMinimumNumberOfNeighbors = numOfNeighborsInCurrentPlace;
}
}
// output
bool isFirstOutput = true;
for(int currentPlace = 0; currentPlace < numOfPlaces; currentPlace++)
{
if(adjacencyList[currentPlace].size() == currentMinimumNumberOfNeighbors)
{
if(!isFirstOutput) { cout << ' '; }
cout << currentPlace + 1;
isFirstOutput = false;
}
}
cout << endl;
}
return 0;
}


My actual solution is actually here.

Happy coding!!!

No comments:

Post a Comment