1. 程式人生 > 其它 >【HZOJ/Tarjan】#A.資訊傳遞

【HZOJ/Tarjan】#A.資訊傳遞

#include<stdio.h>
#include<stack>

namespace bikuhiku{
	template <typename _T> _T gtr(_T &_compare_x,_T &_compare_y) {
		return _compare_x > _compare_y ? _compare_x : _compare_y;
	}
	template <typename _T> _T les(_T &_compare_x,_T &_compare_y) {
		return _compare_x < _compare_y ? _compare_x : _compare_y;
	}
	template <typename _T> void get_int(_T &_data_x) {
		int _signal = 1;
		char _get_c;
		_data_x = 0;
		for(_get_c = getchar();_get_c < '0'||_get_c > '9';_get_c = getchar()) if(_get_c == '-') _signal = -1;
		for(;_get_c >= '0'&&_get_c <= '9';_get_c = getchar()) _data_x = (_data_x<<3)+(_data_x<<1)+(_get_c^48);
		_data_x *= _signal;
		return;
	}
	template <typename _T> void put_int(_T _data_x) {
		if(_data_x > 9) put_int(_data_x/10); 
		putchar((_data_x%10)^48);
		return;
	}
}//申請一塊名稱空間;
using namespace bikuhiku;
using namespace std;

const int z = 262144-65536+4096;
int ans = 0x7f7f7f, n;

int tot;
int to[z], dfn[z], low[z];
stack<int> stk;
bool visit[z];
void tarjan(int &u) {
	dfn[u] = low[u] = ++tot;//初始化時間戳、low;
	stk.push(u);//放入棧;
	visit[u] = true;//標記通入;
	if(!dfn[to[u]]) {
		tarjan(to[u]);//本質上,塔陽建立在dfs的基礎上;
		low[u] = les(low[u],low[to[u]]);
	} else if(visit[to[u]]) {
		low[u] = les(low[u],dfn[to[u]]);
	}//由於只有一條邊,不需要輪迴前向星;
	if(low[u] == dfn[u]) {
		int tmp;
		int cnt = 0;
		do{
			tmp = stk.top();
			stk.pop();
			visit[tmp] = false;
			++cnt;
		} while(tmp != u);//開始找這個強連通分量;
		if(cnt > 1) ans = les(cnt,ans);
	}
	return;
}
int main() {
	get_int(n);
	for(int i = 1;i <= n;++i) 
		get_int(to[i]);
	for(int i = 1;i <= n;++i) 
		if(!dfn[i]) tarjan(i);//如果沒通入,就繼續塔陽;
	put_int(ans);
	return 0;
}