My Solution to "Journey to the Moon" hackerrank question. All testcases pass.
https://www.hackerrank.com/challenges/journey-to-the-moon
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>
#include <numeric>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <fstream>
#include <ctime>
#include <cassert>
using namespace std;
int connected (int a, int b, vector<vector<int>> & v) {
queue<int> q;
vector<int> v1(v.size(), 0);
for (int i = 0; i< v[a].size(); i++) {
q.push(v[a][i]);
}
v1[a] = 1;
while(!q.empty()) {
if (q.front() == b) return 1;
if (v1[q.front()] == 0) {
for (int i = 0; i< v[q.front()].size(); i++) {
q.push(v[q.front()][i]);
}
}
v1[q.front()] = 1;
q.pop();
}
return 0;
}
int main()
{
int N, I;
int c = 0;
long long c1 = 0;
cin >> N >> I;
vector<vector<int> > pairs(N);
vector<vector<int> > country;
vector<int> v(N,0);
vector<int> v1(N,0);
for (int i = 0; i < I; ++i) {
int a, b;
cin >> a >> b;
pairs[a].push_back(b);
pairs[b].push_back(a);
}
long long result = 0;
/** Write code to compute the result using N,I,pairs **/
for (int i = 0; i < N; ++i) {
if (v[i] == 0 && pairs[i].size() > 0) {
vector<int> v2(0);
country.push_back(v2);
country[c].push_back(i);
v1[i] = 1;
for (int j = 0; j<pairs[i].size(); j++) {
if (v1[pairs[i][j]] == 0)
country[c].push_back(pairs[i][j]);
v1[pairs[i][j]] = 1;
}
v[i] = 1;
for(int k = 0; k<country[c].size(); k++) {
if (v[country[c][k]] == 0) {
for (int j = 0; j<pairs[country[c][k]].size(); j++) {
if (v1[pairs[country[c][k]][j]] == 0)
country[c].push_back(pairs[country[c][k]][j]);
v1[pairs[country[c][k]][j]] = 1;
}
}
v[country[c][k]] = 1;
}
c++;
//cout<<"here";
} else {
if (pairs[i].size() == 0) {
//vector<int> v2(0);
//country.push_back(v2);
//country[c].push_back(i);
c1++;
}
}
}
for (int i = 0; i<country.size(); i++) {
for (int j = i +1; j<country.size(); j++) {
result = result + country[i].size() * country[j].size();
}
}
long long temp =0;
for (int i = 0; c1>0 && i<country.size(); i++)
temp = temp + country[i].size();
if (c1> 0) result = result + (c1*(c1-1))/2 + temp*c1;
cout << result <<endl;
return 0;
}
No comments:
Post a Comment