题解 P4306 【[JSOI2010]连通数】

· · 题解

做法:Tarjan缩点+乱搞直接模拟题意统计答案

Tarjan缩点很容易就理解,还不理解可以看看其他题解,这里不再重述

此篇题解我们来暴力地解决最后的统计答案

其实做法很简单:

然而:

小技巧:

听说某些题解不能AC BZOJ QwQ??

特意去BZOJ跑了一遍

CODE

/**************************************************************
    Problem: 2208
    User: Cody010906
    Language: C++
    Result: Accepted
    Time:15852 ms
    Memory:56304 kb
****************************************************************/

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 2e3 + 5, maxm = maxn * (maxn - 1) / 2;
int map[maxn][maxn];
int head[maxm], nxt[maxm], v[maxm], cnt;
int dfn[maxn], low[maxn], stack[maxn], dfx, top;
int scc[maxn], mark;
int vis[maxn], added[maxn][maxn];
int num[maxn], ans[maxn], sum;
int n;

inline void addline(int x, int y) { v[cnt] = y, nxt[cnt] = head[x], head[x] = cnt++; }

inline void tarjan(int x)
{
    dfn[x] = low[x] = ++dfx;
    stack[++top] = x, vis[x] = true;
    for (int i = 1; i <= n; i++)
        if (map[x][i])
        {
            if (!dfn[i])
                tarjan(i), low[x] = min(low[x], low[i]);
            else if (vis[i])
                low[x] = min(low[x], dfn[i]);
        }
    if (dfn[x] == low[x])
    {
        scc[x] = ++mark;
        while (stack[top] != x)
            scc[stack[top]] = mark, vis[stack[top--]] = false;
        vis[x] = false, top--;
        return;
    }
}

inline void dfs(int x, int cnt)
{
    ans[x] += num[x], vis[x] = cnt; //跑到一个点强连通分量x,那x内的所有点都是可以被到达的,也就是一对连通
    for (int i = head[x]; ~i; i = nxt[i])
        if (vis[v[i]] != cnt)
            dfs(v[i], cnt);
    //这里千万不能把vis=其他数了,因为每个点只能算一次,撤掉vis后很可能会有另外一个点跑过来
    return;
}

signed main(void)
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            scanf("%1d", &map[i][j]); //%1d只读一个数字

    for (int i = 1; i <= n; i++) //普普通通跑个tarjan
        if (!dfn[i])
            tarjan(i);

    memset(head, -1, sizeof head); //利用跑出来的强连通分量重建图
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            if (map[i][j] && scc[i] != scc[j] && !added[scc[i]][scc[j]])
                addline(scc[i], scc[j]), added[scc[i]][scc[j]] = true;

    for (int i = 1; i <= n; i++) //统计一个强连通分量里有多少点
        num[scc[i]]++;

    memset(vis, 0, sizeof vis); //统计操作,对于每个点跑dfs模拟统计
    for (int i = 1; i <= n; i++)
        dfs(scc[i], i);
    //记得要从强连通分量出发而不是本身的点,因为已经被重新编号了。
    //第二个元素为每次的操作次数值,用来区别每次操作,这样就不用情况vis了

    for (int i = 1; i <= mark; i++) //累计答案
        sum += ans[i];

    printf("%d\n", sum);
    return 0;
}