传送门

先用tarjan缩点,再记忆话搜索一下

#include <stack>
#include <cstdio>
#include <cstring>
#include <iostream>
#define N 100001
#define min(x, y) ((x) < (y) ? (x) : (y)) int n, cnt, rp, tot, cnt1;
int head1[N], to1[N], next1[N], head[N], to[N], next[N], dfn[N], low[N], belong[N], ans[N], a[N];
bool ins[N];
std::stack <int> s; inline int read()
{
int x = 0, f = 1;
char ch = getchar();
for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1;
for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0';
return x * f;
} inline void add(int x, int y)
{
to[cnt] = y;
next[cnt] = head[x];
head[x] = cnt++;
} inline void add1(int x, int y)
{
to1[cnt1] = y;
next1[cnt1] = head1[x];
head1[x] = cnt1++;
} inline void tarjan(int u)
{
int i, v;
dfn[u] = low[u] = ++rp;
ins[u] = 1;
s.push(u);
for(i = head[u]; i ^ -1; i = next[i])
{
v = to[i];
if(!dfn[v])
{
tarjan(v);
low[u] = min(low[u], low[v]);
}
else if(ins[v]) low[u] = min(low[u], dfn[v]);
}
if(low[u] == dfn[u])
{
tot++;
do
{
v = s.top();
s.pop();
ins[v] = 0;
belong[v] = tot;
} while(u ^ v);
}
} inline int dfs(int u)
{
int i, v;
if(ans[u])
return ans[u];
for(i = head1[u]; i ^ -1; i = next1[i])
{
v = to1[i];
ans[u] = dfs(v);
}
return ans[u] += a[u];
} int main()
{
int i, x, u, v;
memset(head, -1, sizeof(head));
memset(head1, -1, sizeof(head1));
n = read();
for(i = 1; i <= n; i++)
{
x = read();
add(i, x);
}
for(i = 1; i <= n; i++)
if(!dfn[i])
tarjan(i);
for(i = 1; i <= n; i++) a[belong[i]]++;
for(u = 1; u <= n; u++)
for(i = head[u]; i ^ -1; i = next[i])
{
v = to[i];
if(belong[u] ^ belong[v])
add1(belong[u], belong[v]);
}
for(i = 1; i <= n; i++)
printf("%d\n", dfs(belong[i]));
return 0;
}

  

最新文章

  1. Laravel 5.3 auth中间件底层实现详解
  2. Marshal的简单使用
  3. Spark入门实战系列--2.Spark编译与部署(中)--Hadoop编译安装
  4. Pythonj~module
  5. DataTable to byte[]、DataTable to XML(string)
  6. 我的Fitbit Force手环使用体验
  7. Hdu 1506 Largest Rectangle in a Histogram 分类: Brush Mode 2014-10-28 19:16 93人阅读 评论(0) 收藏
  8. Activity生命周期与状态保存
  9. codebook法分割前景目标
  10. web项目启动,运行方法
  11. shell学习指南-阅读笔记
  12. 移植u-boot-2012.04.01到JZ2440
  13. Spring Boot 2.x 综合示例-整合thymeleaf、mybatis、shiro、logging、cache开发一个文章发布管理系统
  14. 深度理解 React Suspense(附源码解析)
  15. Browser Page Parsing Details
  16. 洛谷P3959 宝藏
  17. 最短路经算法简介(Dijkstra算法,A*算法,D*算法)
  18. 【Mybatis】【2】处理大于号小于号及其他特殊字符
  19. tcp的发送端一个小包就能打破对端的delay_ack么?
  20. 百度搜索_如何打开Intellij IDEA的代码提示功能?

热门文章

  1. 关于搭建系统直播和Thinkphp的杂谈(持续更新)
  2. 【笨办法学Python】习题11:打印出改变了的输入
  3. Java jar包查询下载方法
  4. selenium-Python之进行文件的上传和下载文件
  5. Linux OpenGL 实践篇-12-procedural-texturing
  6. Go 1.4 正式版发布,官方正式支持 Android
  7. 说说三四月的app审核中的几个坑
  8. Objective-C中的命名前缀说明
  9. 优先队列的使用——Expedition
  10. flex常用属性