lightoj1003 Drunk

思路:判断途中是否有环,有就是Yes,否则就是No。

求个scc就好了,水题。

// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
// #define DEBUG
#ifdef DEBUG
#define debug(...) printf( __VA_ARGS__ )
#else
#define debug(...)
#endif
#define MEM(x,y) memset(x, y,sizeof x)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> ii;
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
map<string,int> mp;
const int maxn = 20010;
int head[maxn], nxt[maxn], to[maxn], tol;
void Add(int u,int v){
	to[tol] = v;
	nxt[tol] = head[u];
	head[u] = tol++;
}
int dfn[maxn], low[maxn];
bool vis[maxn];
int scc;
stack<int> st;
int Time;
void dfs(int u){
	vis[u] = true;
	dfn[u] = low[u] = Time++;
	st.push(u);
	for (int i = head[u];i != -1;i = nxt[i]){
		int v = to[i];
		if (dfn[v] == -1){
			dfs(v);
			low[u] = min(low[u], low[v]);
		}else if (vis[v] && dfn[v] < low[u])
			low[u] = dfn[v];
	}
	if (dfn[u] == low[u]){
		scc++;
		while(true){
			int v = st.top();
			st.pop();
			vis[v] = false;
			if (u == v) break;
		}
	}
}
int main()
{	
	// freopen("in.txt","r",stdin);
	// freopen("out.txt","w",stdout);
	int t;
	cin >> t;
	int icase = 0;
	while(t--){
		mp.clear();
		int m;
		cin >> m;
		int cnt = 0;
		string a, b;
		tol = 0;
		MEM(head, -1);
		for (int i = 1;i <= m;++i){
			cin >> a >> b;
			if (!mp[a]) mp[a] = ++cnt;
			if (!mp[b]) mp[b] = ++cnt;
			Add(mp[a], mp[b]);
		}
		scc = 0;
		MEM(vis, false);
		MEM(dfn, -1);
		for (int i = 1;i <= cnt;++i){
			if (dfn[i] == -1) dfs(i);
		}
		printf("Case %d: ", ++icase);
		if (scc < cnt) puts("No");
		else puts("Yes");
	}
	return 0;
}


你可能感兴趣的:(强连通分量,lightoj)