关于时间复杂度???
  • 板块灌水区
  • 楼主Zhang_Wenjie
  • 当前回复2
  • 已保存回复2
  • 发布时间2024/6/1 21:12
  • 上次更新2024/6/3 13:58:53
查看原帖
关于时间复杂度???
481621
Zhang_Wenjie楼主2024/6/1 21:12

为什么会 TLE?我真的有点蒙了...

这是 CF上的一道题 Rudolf and Subway

点数边数都是 2e5, T 是 1e4

#include <bits/stdc++.h>
#define re register int 
using namespace std;
const int N = 4e5 + 10, M = 4e5 + 10;

struct edge
{
	int x, y, c;
}e[M];
int dep[N], color[N], idx;
int T, n, m, s, t;
vector<int> g[N], path;

inline void build()
{
	for (re i = 1; i <= m; i ++)
	{
		int x = e[i].x, y = e[i].y, c = e[i].c;
		if (!color[c]) color[c] = ++ idx;
		g[n + color[c]].push_back(x);
		g[n + color[c]].push_back(y);
		g[x].push_back(n + color[c]);
		g[y].push_back(n + color[c]);
	}
/*	
	for (re i = n + 1; i <= n + 3; i ++)
		for (re j = 0; j < g[i].size(); j ++)
			cout << i - n << ' ' << g[i][j] << '\n';
*/
}

inline void bfs()
{
	queue<int> q;
	
	q.push(s);
	dep[s] = 1;
	
	while (!q.empty())
	{
		int x = q.front(); q.pop();
		
		for (re i = 0; i < g[x].size(); i ++)
		{
			int y = g[x][i];
			
			if (!dep[y])
			{
				dep[y] = dep[x] + 1;
				q.push(y);
			}
		}
	}
}

inline void print()
{
	int u = t;
	path.push_back(u);
	
	while (u != s)
	{
		for (re i = 0; i < g[u].size(); i ++)
		{
			int v = g[u][i];
			
			if (dep[v] + 1 == dep[u])
			{
				path.push_back(v);
				u = v;
			}
		}
	}
	cout << path.size() / 2 << '\n';
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
	
	cin >> T;
	
	while (T --)
	{
		memset(e, 0, sizeof(e));
		memset(dep, 0, sizeof(dep));
		memset(color, 0, sizeof(color));
		idx = 0;
		path.clear();
		
		cin >> n >> m;
		for (re i = 1; i <= m; i ++)
			cin >> e[i].x >> e[i].y >> e[i].c;
		cin >> s >> t;
		
		build();
		bfs();
		print();
		
		for (re i = 1; i <= n + m + 1; i ++) g[i].clear();	
	}
	
	return 0;
}
2024/6/1 21:12
加载中...