# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1139858 | tmm | Monthly railway pass (LMIO18_menesinis_bilietas) | C++20 | 0 ms | 0 KiB |
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
using namespace std;
struct drum{
int x;
int y;
bool t;
};
const string file = "b";
const int N_max = 500005;
ifstream fin(file + ".in");
ofstream fout(file + ".out");
int n, m;
drum muc[N_max];
int father[N_max];
int nodes[N_max];
int fr[N_max];
map<pair<int, int>, int> already_added;
void reading(){
cin >> n >> m;
for(int i = 1; i <= n; i++) {
father[i] = i;
nodes[i] = 1;
}
for(int i = 1; i <= m; i++){
char c;
cin >> muc[i].x >> muc[i].y >> c;
muc[i].t = (c == 'T'? 1: 0);
}
}
int Sfather(int x){
if(x == father[x])
return x;
int f = Sfather(father[x]);
father[x] = f;
return father[x];
}
void join(int x1, int x2, int&k){
int f1 = Sfather(x1);
int f2 = Sfather(x2);
if(f1 == f2) return;
k--;
if(nodes[f1] > nodes[f2]){
father[f2] = f1;
nodes[f1] += nodes[f2];
}else{
father[f1] = f2;
nodes[f2] += nodes[f1];
}
}
int main() {
reading();
int k = n;
for(int i = 1; i <= m; i++){
if(muc[i].t == 1)
join(muc[i].x, muc[i].y, k);
}
for(int i = 1; i <= m; i++){
if(muc[i].t == 0) {
int f1 = Sfather(muc[i].x), f2 = Sfather(muc[i].y);
if(f1 == f2) continue;
int mf = min(f1, f2), Mf = max(f1, f2);
if(already_added[{mf, Mf}] == 1)continue;
already_added[{mf,Mf}] = 1;
fr[f1]++; fr[f2]++;
}
}
if(k == 1) {
cout << n;
return 0;
}
int sol = 0;
for(int i = 1; i <= n; i++){
if(fr[i] == k - 1)
sol += nodes[i];
}
cout << sol;
}