一名苦逼的OIer,想成为ACMer

Iowa_Battleship

洛谷3387 【模板】缩点

原题链接

做了挺多强连通分量缩点题,结果模板还晾着。。
\(tarjan\)找强连通缩点,然后拓扑排序\(DP\)就好。

#include<cstdio>
using namespace std;
const int N = 1e4 + 10;
const int M = 1e5 + 10;
struct eg {
	int x, y;
};
eg a[M];
int fi[N], di[M], ne[M], cfi[N], cdi[M], cne[M], dfn[N], low[N], sta[N], bl[N], po[N], S[N], ru[N], q[M], su[N], l, lc, tp, ti, SCC, ma;
bool v[N];
inline int re()
{
	int x = 0;
	char c = getchar();
	bool p = 0;
	for (; c < '0' || c > '9'; c = getchar())
		p |= c == '-';
	for (; c >= '0' && c <= '9'; c = getchar())
		x = x * 10 + c - '0';
	return p ? -x : x;
}
inline void add(int x, int y)
{
	di[++l] = y;
	ne[l] = fi[x];
	fi[x] = l;
}
inline void add_c(int x, int y)
{
	cdi[++lc] = y;
	cne[lc] = cfi[x];
	cfi[x] = lc;
}
inline int minn(int x, int y)
{
	return x < y ? x : y;
}
inline int maxn(int x, int y)
{
	return x > y ? x : y;
}
void tarjan(int x)
{
	int i, y;
	dfn[x] = low[x] = ++ti;
	sta[++tp] = x;
	v[x] = 1;
	for (i = fi[x]; i; i = ne[i])
		if (!dfn[y = di[i]])
		{
			tarjan(y);
			low[x] = minn(low[x], low[y]);
		}
		else
			if (v[y])
				low[x] = minn(low[x], dfn[y]);
	if (!(dfn[x] ^ low[x]))
	{
		SCC++;
		do
		{
			y = sta[tp--];
			bl[y] = SCC;
			v[y] = 0;
			S[SCC] += po[y];
		} while (x ^ y);
		ma = maxn(ma, S[SCC]);
	}
}
void topsort()
{
	int i, x, y, head = 0, tail = 0;
	for (i = 1; i <= SCC; i++)
		if (!ru[i])
		{
			q[++tail] = i;
			su[i] = S[i];
		}
	while (head ^ tail)
	{
		x = q[++head];
		for (i = cfi[x]; i; i = cne[i])
		{
			ru[y = cdi[i]]--;
			if (!ru[y])
				q[++tail] = y;
			su[y] = maxn(su[y], su[x] + S[y]);
			ma = maxn(ma, su[y]);
		}
	}
}
int main()
{
	int i, n, m, x, y;
	n = re();
	m = re();
	for (i = 1; i <= n; i++)
		po[i] = re();
	for (i = 1; i <= m; i++)
	{
		a[i].x = re();
		a[i].y = re();
		add(a[i].x, a[i].y);
	}
	for (i = 1; i <= n; i++)
		if (!dfn[i])
			tarjan(i);
	for (i = 1; i <= m; i++)
	{
		x = bl[a[i].x];
		y = bl[a[i].y];
		if (x ^ y)
		{
			add_c(x, y);
			ru[y]++;
		}
	}
	topsort();
	printf("%d", ma);
	return 0;
}

posted on 2018-09-21 13:24  Iowa_Battleship  阅读(106)  评论(0编辑  收藏  举报

导航