题解 P4306 【[JSOI2010]连通数】
UPD:19/11/15 根据 @wlzhouzhuan 提供的数据修改代码,更新 LaTeX。
这题数据好水啊,能让暴力拿82pts,一个完全图就直接卡飞好吧。。
题目分析:
求"图中可达顶点对个的个数",题目说的很清晰了,没什么好分析的 ,走个过场。
82pts 暴力:
每个点dfs遍历统计能到达的点数,最后求和,(要是在考场上有这个分数也挺不错)。
82pts 提交记录
核心代码:
int dfs(int p) {
int res = 1;
for(int i = 1;i <= n;i++)
if(mp[p][i] && !vis[i]) {
vis[i] = 1;
res += dfs(i);
}
return res;
}
int main() {
//省去读入
RS int ans = 0;
for(RS int i = 1;i <= n;i++) {
memset(vis, 0, sizeof(vis));
vis[i] = 1; ans += dfs(i);
}
printf("%d", ans);
return 0;
}
如果是一个满图
100pts \text{Tarjan} + 拓扑排序
然后我们要想正解,怎么优化时间复杂度。
题面既然讲联通,那还能想到什么呢?强连通分量。
OK,
然后对于每条DAG上的边(最多
但是对于随机数据,
最后枚举所有强连通分量,若能从分量
AC 记录
代码实现(54ms in total):
#pragma GCC optimize("Ofast,fast-math,unroll-loops")
#include <bits/stdc++.h>
#define RS register
#define N 2005
using namespace std;
int n, mp[N][N], cmp[N][N], ans;
int dfn[N], low[N], co[N], tim, col;
int du[N], sum[N], stk[N], top;
bool cvis[N];
void tarjan(int x) {//缩点
dfn[x] = low[x] = ++tim;
stk[++top] = x;
for(RS int i = 1;i <= n;i++) {
if(!mp[x][i]) continue;
if(!dfn[i]) {
tarjan(i);
if(low[i] < low[x]) low[x] = low[i];
} else if(!co[i] && dfn[i] < low[x])
low[x] = dfn[i];
}
if(dfn[x] == low[x]) {
co[x] = ++col; sum[col] = 1;
while(stk[top] != x) co[stk[top--]] = col, sum[col]++;
top--; cmp[col][col] = 1;//自己能到达自己
}
}
//懒得敲bfs就用dfs+vis代替了。。
void dfs(int cx) {
cvis[cx] = 1;
for(RS int i = 1;i <= col;i++) {
if(!cmp[cx][i]) continue;
if(!cvis[i]) dfs(i);
for(RS int j = 1;j <= col;j++)
if(cmp[i][j]) cmp[cx][j] = 1;
}
}
inline bool read_bool() {
RS char c(getchar());
while(!isdigit(c)) c = getchar();
return c == '1';//万物皆可快读
}
int main() {
scanf("%d", &n);
for(RS int i = 1;i <= n;i++)
for(RS int j = 1;j <= n;j++)
mp[i][j] = read_bool();
for(RS int i = 1;i <= n;i++)
if(!dfn[i]) tarjan(i);//注意联通性
//接下来转移边到新图上O(n^2)(如果是存了边就是O(m))
for(RS int i = 1;i <= n;i++)
for(RS int j = 1;j <= n;j++)
if(mp[i][j] && !cmp[co[i]][co[j]])
cmp[co[i]][co[j]] = 1, du[co[j]]++;
for(RS int i = 1;i <= col;i++)
if(!du[i]) dfs(i);
for(RS int i = 1;i <= col;i++)
for(RS int j = 1;j <= col;j++)
if(cmp[i][j]) ans += sum[i] * sum[j];
printf("%d", ans);
return 0;
}
最后附上把
将所有节点排成一条链,每个点都向后面所有的节点连满边,那么
后记:
看到后面题解有 dalao 靠 DP 转移但被 Hack 的,其实我也想过既然是一个 DAG ,能不能搞个什么 DP 弄成
对于讨论区的新数据