#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class DSU
{
public :
unordered_map<string,int> size;
unordered_map<string,string> parent;
DSU(unordered_set<string> ele)
{
for(auto it : ele)
{
parent[it]=it;
size[it] =1;
}
}
string findParent(string curr)
{
if(curr==parent[curr])
return curr;
else
{
return parent[curr]=findParent(parent[curr]);
}
}
void doUnion (string firstPerson,string secondPerson)
{
string firstPersonParent = findParent(firstPerson);
string secondPersonParent = findParent(secondPerson);
if(firstPersonParent==secondPersonParent)
return;
if(size[firstPersonParent] > size[secondPersonParent])
{
size[firstPersonParent] += size[secondPersonParent];
parent[secondPersonParent] = firstPersonParent;
}
else
{
size[secondPersonParent] += size[firstPersonParent];
parent[firstPersonParent] = secondPersonParent;
}
}
};
string findMinTime(vector<string> logs)
{
vector<vector<string>> adj;
unordered_set<string> friends;
for(auto it : logs)
{
stringstream ss(it);
string firstPerson;
string secondPerson;
string relation;
string time;
ss>>time>>firstPerson>>relation>>secondPerson;
vector<string> temp;
temp.push_back(time);
temp.push_back(firstPerson);
temp.push_back(secondPerson);
friends.insert(secondPerson);
friends.insert(firstPerson);
adj.push_back(temp);
}
DSU dsu(friends);
int total = friends.size();
for(auto it : adj )
{
string time = it[0];
string firstPerson = it[1];
string secondPerson = it[2];
if(dsu.findParent(firstPerson)!= dsu.findParent(secondPerson))
{
dsu.doUnion(firstPerson,secondPerson);
total--;
if(total==1)
return time;
}
}
return "No connected";
}
int main() {
// your code goes here
vector<string> logs = {
"167001 Alice shared-ride-with Bob",
"167003 Charlie shared-ride-with Dan",
"167008 Bob shared-ride-with Charlie",
"167010 Alice shared-ride-with Eve",
"167020 Bob shared-ride-with Dan"
};
cout<<findMinTime (logs);
return 0;
}