1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| #include <stack> #include <cctype> #include <cstdio> #include <algorithm> #include <iostream> #include <vector> #include <cstring> #include <climits> #include <queue> #include <string> #include <ctime> #include <iomanip> #include <cmath> #include <cstdlib> using namespace std; bool iosig; char ch; template<class T> inline void read(T &x) { iosig = 0, x = 0; do { ch = getchar(); if (ch == '-') iosig = true; } while (!isdigit(ch)); while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ '0'), ch = getchar(); if (iosig) x = -x; } const int MAXN = 20010; struct Node { int v, index; bool flag; Node(int v, int index) : v(v), index(index), flag(0) {} }; vector<Node> edge[MAXN]; inline void addEdge(int u, int v) { edge[u].push_back(Node(v, edge[v].size())); if (u == v) edge[u].back().index++; edge[v].push_back(Node(u, edge[u].size() - 1)); } int dfn[MAXN], low[MAXN], idx, inComponent[MAXN]; int componentSize[MAXN], componentNumber, ans; stack<int> st; inline void tarjan(int u) { dfn[u] = low[u] = ++idx; st.push(u); register int v; for (register int e = 0; e < edge[u].size(); e++) { Node *x = &edge[u][e]; if (x->flag) continue; x->flag = true; edge[x->v][x->index].flag = true; v = x->v; if (!dfn[v]) { tarjan(v); low[u] = min(low[u], low[v]); } else if (!inComponent[v]) low[u] = min(low[u], low[v]); } if (dfn[u] == low[u]) { componentNumber++; do { v = st.top(), st.pop(); componentSize[componentNumber]++; inComponent[v] = componentNumber; } while (v != u); ans -= componentSize[componentNumber] * (componentSize[componentNumber] - 1) >> 1; } } int n, m; int main() { read(n), read(m); for (register int i = 0, u, v; i < m; i++) read(u), read(v), addEdge(u, v); ans = n * (n - 1) >> 1; for (register int i = 1; i <= n; i++) if (!dfn[i]) tarjan(i); cout << ans; return 0; }
|