Luogu P4306 JSOI2010 连通数
tarjan有向图缩点的基础应用。把原图中某点的连通数转化为反向图中”能够到达某点的个数“。缩点后,每个新点的贡献等于
原dcc大小 * f[i]
其中f[i]表示(包括该点自身)通向该点的点的个数。设u点为v的入度,满足转移方程:
所以我们按照拓扑序dp求解即可。f[i]的初值设为该分量的节点数。
这个题引出一个很重要的想法:如何避免两个强连通分量缩点时连有重边?对于2000的数据范围,一个二维布尔数组完全可以承受,但显然有更普适的优秀做法,这就是Hash。去重边实际上是二元组的判重问题,我们只需要一个合适的“进位”技术,就可以保证任意两个二元组所映射的键值是绝不相同的。如果key值太大,就要套用Hash表解决了。
- #include <iostream>
- #include <cstdio>
- #include <cstring>
- #include <queue>
- #include <cctype>
- #define maxn 2010
- using namespace std;
- template <typename T>
- void read(T &x) {
- x = 0;
- char ch = getchar();
- while (!isdigit(ch))
- ch = getchar();
- while (isdigit(ch))
- x = x * 10 + (ch ^ 48),
- ch = getchar();
- return;
- }
- struct E {
- int to, nxt;
- } edge[maxn * maxn], edge2[maxn * maxn];
- int n, head[maxn], top, head2[maxn], top2;
- inline void insert(int u, int v) {
- edge[++top] = (E) {v, head[u]};
- head[u] = top;
- }
- inline void insert2(int u, int v) {
- edge2[++top2] = (E) {v, head2[u]};
- head2[u] = top2;
- }
- int dfn[maxn], low[maxn], timer,
- sta[maxn], stp,
- c[maxn], cnt,
- w[maxn];
- bool ins[maxn];
- void tarjan_dfs(int u) {
- dfn[u] = low[u] = ++timer;
- sta[++stp] = u, ins[u] = true;
- for (int i = head[u]; i; i = edge[i].nxt) {
- int v = edge[i].to;
- if (!dfn[v])
- tarjan_dfs(v), low[u] = min(low[u], low[v]);
- else if (ins[v])
- low[u] = min(low[u], dfn[v]);
- }
- if (dfn[u] == low[u]) {
- ++cnt;
- int x;
- do {
- x = sta[stp--];
- ins[x] = false;
- c[x] = cnt;
- ++w[cnt];
- } while (x != u);
- }
- }
- void tarjan() {
- for (int i = 1; i <= n; ++i)
- if (!dfn[i]) tarjan_dfs(i);
- }
- namespace Hash_table {
- // const int Size(23333309), step = 7;//空间足够,不用取模
- bool tb[4004001];
- inline int H (int u, int v) {
- return u * 2001 + v;
- }
- bool Hash(int u, int v) {
- int key = H(u, v);
- if (tb[key]) return false;
- tb[key] = true;
- return true;
- }
- } using namespace Hash_table;
- int ind[maxn];
- //bool done[maxn][maxn];//Hash更为优秀
- void build() {
- for (int u = 1; u <= n; ++u)
- for (int i = head[u]; i; i = edge[i].nxt) {
- int v = edge[i].to;
- if (c[u] != c[v] && Hash(c[u], c[v])) {
- insert2(c[u], c[v]);
- ++ind[c[v]];
- }
- }
- }
- long long sum = 0;
- long long f[maxn];
- queue<int> que;
- void dp() {
- for (int i = 1; i <= cnt; ++i) {
- f[i] = w[i];
- if (!ind[i]) {
- sum += w[i] * w[i];
- que.push(i);
- }
- }
- while (!que.empty()) {
- int u = que.front(); que.pop();
- for (int i = head2[u]; i; i = edge2[i].nxt) {
- int v = edge2[i].to;
- f[v] += f[u];
- --ind[v];
- if (!ind[v]) {
- sum += w[v] * f[v];
- que.push(v);
- }
- }
- }
- }
- int main() {
- read(n);
- for (int u = 1; u <= n; ++u)
- for (int v = 1; v <= n; ++v) {
- char ch = getchar();
- while (!isdigit(ch)) ch = getchar();
- if (ch == '1') insert(v, u);//反向存图
- }
- tarjan();
- build();
- dp();
- printf("%lld", sum);
- return 0;
- }