Journey to the Moon

  • + 0 comments

    include

    using namespace std;

    string ltrim(const string &); string rtrim(const string &); vector split(const string &);

    long long journeyToMoon(int n, vector> astronaut) { vector> adj(n); for (auto &e : astronaut) { int u = e[0], v = e[1]; adj[u].push_back(v); adj[v].push_back(u); } vector vis(n, 0); vector comp; comp.reserve(n); for (int i = 0; i < n; ++i) { if (vis[i]) continue; int sz = 0; stack st; st.push(i); vis[i] = 1; while (!st.empty()) { int u = st.top(); st.pop(); ++sz; for (int v : adj[u]) { if (!vis[v]) { vis[v] = 1; st.push(v); } } } comp.push_back(sz); } long long total = 0; long long prefix = 0; for (int s : comp) { total += prefix * (long long)s; prefix += s; } return total; }

    int main() { ofstream fout(getenv("OUTPUT_PATH"));

    string first_multiple_input_temp;
    getline(cin, first_multiple_input_temp);
    
    vector<string> first_multiple_input = split(rtrim(first_multiple_input_temp));
    
    int n = stoi(first_multiple_input[0]);
    int p = stoi(first_multiple_input[1]);
    
    vector<vector<int>> astronaut(p);
    for (int i = 0; i < p; i++) {
        astronaut[i].resize(2);
        string astronaut_row_temp_temp;
        getline(cin, astronaut_row_temp_temp);
        vector<string> astronaut_row_temp = split(rtrim(astronaut_row_temp_temp));
        for (int j = 0; j < 2; j++) {
            int astronaut_row_item = stoi(astronaut_row_temp[j]);
            astronaut[i][j] = astronaut_row_item;
        }
    }
    
    long long result = journeyToMoon(n, astronaut);
    fout << result << "\n";
    fout.close();
    
    return 0;
    

    }

    string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) ); return s; }

    string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), s.end() ); return s; }

    vector split(const string &str) { vector tokens; string::size_type start = 0; string::size_type end = 0; while ((end = str.find(" ", start)) != string::npos) { tokens.push_back(str.substr(start, end - start)); start = end + 1; } tokens.push_back(str.substr(start)); return tokens; }