UVa247 - Calling Circles

本文介绍了一个使用Tarjan算法寻找强连通分量的C++实现案例。通过输入节点数及边的关系来构建图,并利用Tarjan算法进行深度优先搜索,找出所有的强连通分量。该程序还包含了文件读取功能,方便从外部文件加载数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值