UVa247 - Calling Circles

#include <cstdio>
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <cstring>
#include <vector>
#include <stack>
#include <algorithm>

using namespace std;

const int N = 30;

map<string, int> strMap;
map<int, string> intMap;

int idx(string &s);
int f[N][N];
int dfn[N], low[N];
int dfsclock;
stack<int> s;
int n, m;
bool inStack[N];

void Tarjan(int u);

int main()
{
	string s1, s2;
	int t = 1;

#ifndef ONLINE_JUDGE
	//freopen("d:\\OJ\\uva_in.txt", "r", stdin);
	ifstream cin("d:\\OJ\\uva_in.txt");
#endif

	while (cin >> n >> m) {
		if (n == 0 && m == 0) break;
		memset(f, 0x00, sizeof(f));
		strMap.clear();
		intMap.clear();
		while (m--) {
			cin >> s1 >> s2;
			int u = idx(s1), v = idx(s2);
			f[u][v] = 1;
		}


		memset(dfn, 0x00, sizeof(dfn));
		memset(low, 0x00, sizeof(low));
		memset(inStack, false, sizeof(inStack));
		while (!s.empty()) s.pop();
		dfsclock = 0;

		if (t > 1) cout << endl;

		cout << "Calling circles for data set " << t++ << ":" << endl;
		for (int i = 0; i < n; i++) {
			if (!dfn[i]) Tarjan(i);
		}


	}
	return 0;
}

int idx(string &s)
{
	if (strMap.count(s)) return strMap[s];
	int size = strMap.size();

	strMap[s] = size;
	intMap[size] = s;
	return size;
}

void Tarjan(int u)
{
	dfn[u] = low[u] = ++dfsclock;
	s.push(u);
	inStack[u] = true;

	for (int v = 0; v < n; v++) {
		if (f[u][v] && !dfn[v]) {
			Tarjan(v);
			low[u] = min(low[u], low[v]);
		} else if (f[u][v] && inStack[v]) {
			low[u] = min(low[u], dfn[v]);
		}
	}

	if (dfn[u] == low[u]) {
		vector<int> intVec;
		while (!s.empty()) {
			int v = s.top(); s.pop();
			inStack[v] = false;
			intVec.push_back(v);
			if (v == u) break;
		}

		for (size_t i = 0; i < intVec.size(); i++) {
			if (i) cout << ", ";
			cout << intMap[intVec[i]];
		}
		cout << endl;
	}
}

你可能感兴趣的:(UVa247 - Calling Circles)