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