求dalao分析时间复杂度,我怀疑哪里假了
查看原帖
求dalao分析时间复杂度,我怀疑哪里假了
1052511
XinFengIneverleft楼主2023/11/17 10:41

翻讨论区看见这位的 O(n²) 做法过了,但是我写的 O(n²) 就只有45pts/kk

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

const int N = 1e4 + 5;
const int mod = 1e9 + 7;

int n, r, m;;
vector<int> g[N];

queue<int> q;
int depth[N], fa[N][15];

int cnt[N];

inline void add(int x, int y)
{
	g[x].push_back(y);
}

inline void init()
{
	cin >> n >> r >> m;
	for (int i = 1; i <= n - 1; i++)
	{
		int a, b;
		cin >> a >> b;
		add(a, b), add(b, a);
	}
}

inline void bfs(int root)
{
	for (int i = 1; i <= n; i++)
		depth[i] = 0x3f3f3f3f;
	depth[root] = 1, depth[0] = 0;

	q.push(root);
	while (!q.empty())
	{
		int pos = q.front();
		q.pop();

		for (int i = 0; i < g[pos].size(); i++)
		{
			int to = g[pos][i];
			if (depth[to] > depth[pos] + 1)
			{
				depth[to] = depth[pos] + 1;
				q.push(to);
				fa[to][0] = pos;
				for (int j = 1; j <= 14; j++)
					fa[to][j] = fa[fa[to][j - 1]][j - 1];
			}
		}
	}
}

int lca(int a, int b)
{
	if (depth[a] < depth[b])
		swap(a, b);

	for (int i = 14; i >= 0; i--)
		if (depth[fa[a][i]] >= depth[b])
			a = fa[a][i];

	if (a == b)
		return a;

	for (int i = 14; i >= 0; i--)
		if (fa[a][i] != fa[b][i])
		{
			a = fa[a][i];
			b = fa[b][i];
		}

	return fa[a][0];
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);

	init();
	bfs(r);

	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++)
			cnt[lca(i, j)]++;

	while (m--)
	{
		int p;
		cin >> p;
		cout << cnt[p] % mod << '\n';
	}
	return 0;
}
2023/11/17 10:41
加载中...