【luogu P2746 [USACO5.3]校园网Network of Schools】 题解

题目链接:https://www.luogu.org/problemnew/show/P2812
注意:判断出入度是否为0的时候枚举只需到颜色的数量。
坑点:当只有一个强连通分量时,不需要再添加新边。即子任务B ans = 0。
子任务B证明:若每个点都相连通,出入度都必须为1。
保证所有点的出入度都>1就OK。
所以需要找一下出度为0和入度为0的点再取一个max即可。

#include <stack>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100000 + 10;
struct edge{
	int from, to, next;
}e[maxn<<2];
int head[maxn], cnt;
bool vis[maxn];
int n, dfn[maxn], low[maxn], tim, color[maxn], num, chudu[maxn], rudu[maxn], runum, chunum;

stack<int> s;
void add(int u, int v)
{
	e[++cnt].from = u;
	e[cnt].next = head[u];
	e[cnt].to = v;
	head[u] = cnt;
}
void tarjan(int x)
{
	dfn[x] = low[x] = ++tim;
	s.push(x); vis[x] = 1;
	for(int i = head[x]; i != -1; i = e[i].next)
	{
		int v = e[i].to;
		if(!dfn[v])
		{
			tarjan(v);
			low[x] = min(low[x], low[v]);
		}
		else if(vis[v])
		{
			low[x] = min(low[x], low[v]);
		}
	}
	if(dfn[x] == low[x])
	{
		color[x] = ++num;
		vis[x] = 0;
		while(s.top() != x)
		{
			color[s.top()] = num;
			vis[s.top()] = 0;
			s.pop();
		}
		s.pop();
	}
}
int main()
{
	int m;
	memset(head, -1, sizeof(head));
	scanf("%d",&n);
	for(int i = 1; i <= n; i++)
	{
		int u;
		while(scanf("%d",&u) && u != 0)
		add(i, u);
	}
	for(int i = 1; i <= n; i++)
		if(!dfn[i]) tarjan(i);
	for(int i = 1; i <= n; i++)
		for(int j = head[i]; j != -1; j = e[j].next)
		{
			int v = e[j].to;
			if(color[v] != color[i])
			{
				chudu[color[i]]++;
				rudu[color[v]]++;
			}
		}
	for(int i = 1; i <= num; i++)
	{
		if(!rudu[i]) runum++;
		if(!chudu[i]) chunum++;
	}
	for(int i = 2; i <= n; i++)
	{
		if(color[i] != color[i-1])
		{
			printf("%d\n%d",runum, max(runum, chunum));
			return 0;
		}
	}
	printf("%d\n%d",runum,0);	
	return 0;
}
posted @ 2018-07-26 16:11  Misaka_Azusa  阅读(157)  评论(0编辑  收藏  举报
Live2D