为啥我的dfs找环总是tle,我觉得复杂度应该不会比Floyd大啊
查看原帖
为啥我的dfs找环总是tle,我觉得复杂度应该不会比Floyd大啊
237893
donkeys楼主2020/8/29 10:39
#include<iostream>
#include<fstream>
#include<algorithm>
#include<cstring>
using namespace std;
//ifstream cin("data.in");
const int N = 102, M = 5003;
int m, n, ans = 0x7f7f7f7f;
bool to[N][N];
int edge[N][N], sum[N], num[N];
int pre[N], cost[N];
bool circle[N];
void find(int now, int goal, int base)
{
	int add = base;
	add += sum[now] - sum[goal];
	circle[goal] = 1;
	ans = min(add, ans);
	return;
}
void dfs(int now)
{
	for (int i = 1; i <= n; i++)
	{
		if (!to[now][i])//不能去
			continue;
		if (i == pre[now]/*||circle[to[i]]*/)//刚过来的节点或者是环
			continue;
		else if (pre[i])//访问过
		{
			find(now, i, edge[now][i]);
			continue;
		}
		pre[i] = now;
		sum[i] = sum[pre[i]] + edge[now][i];//前缀和
		dfs(i);
		pre[i] = 0;
	}
}
void add(int f, int t, int v)
{
	to[f][t] = 1, edge[f][t] = min(v, edge[f][t]);
}
int main()
{
	ios::sync_with_stdio(false);
	memset(edge, 0x3f, sizeof(edge));
	cin >> n >> m;
	for (int i = 0, a, b, c; i < m; i++)
	{
		cin >> a >> b >> c;
		add(a, b, c), add(b, a, c);
	}
	dfs(1);
	if (ans == 0x7f7f7f7f)
		cout << "No solution.";
	else
		cout << ans;
	return 0;
}

只能过前四个点,随机数据基本上m=100就炸了,n=100倒是没事

2020/8/29 10:39
加载中...