This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//https://oj.uz/problem/view/JOI14_friends
#include<bits/stdc++.h>
const int N = 1e5 + 5;
using namespace std;
vector <int> adj[N];
int n, m, pset[N], siz[N];
long long ans;
bool check[N];
int findset(int i) {return ((pset[i] == i) ? i : pset[i] = findset(pset[i]));}
bool unionset(int i, int j){
i = findset(i); j = findset(j);
if (i == j) return false;
siz[j] += siz[i];
pset[i] = j;
return true;
}
int main(){
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= m; i++){
int u, v; cin >> u >> v;
adj[u].push_back(v);
}
for (int i = 1; i <= n; i++) pset[i] = i, siz[i] = 1;
for (int u = 1; u <= n; u++){
if ((int)adj[u].size() >= 2){
int x = adj[u][0]; check[x] = true;
for (int i = 1; i < (int)adj[u].size(); i++){
int v = adj[u][i];
check[v] = true;
unionset(x, v);
}
}
}
queue <int> mq;
for (int i = 1; i <= n; i++) if (check[i]) mq.push(i);
while (mq.size()){
int u = mq.front(); mq.pop();
for (int i = 0; i < (int)adj[u].size(); i++){
int v = adj[u][i];
if (!check[v]) check[v] = true, mq.push(v);
unionset(u, v);
}
}
for (int i = 1; i <= n; i++) if (pset[i] == i) ans += 1LL * siz[i] * (siz[i] - 1);
for (int i = 1; i <= n; i++) if (pset[i] == i && siz[i] == 1) ans += (int)adj[i].size();
cout << ans << "\n";
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |