跳到正文

题解

P4185题解

naober约 3 分钟
原文
文章信息与版本

文章信息

发布
2024年6月1日
收录
2025年12月12日
更新
2026年10月28日
篇幅
约 3 分钟
获赞
2
题目
P4185

版本

  1. v1当前

样例解释

先根据输入建图

C++
 1 ---(3)--- 2 -------(4)-- 4
             |
     	     |
   	         (2)
             |
             3
   

首先我们知道(1 2)(2 4)(2 3)的关联度

C++
- 3 - -
3 - 2 4
- 2 - - 
- 4 - -

那么,像 1 4这种题目每个出的应该是多少?

观察题目可知两个视频的关联度是他们路径中边权最小 的权值

因此可得下表

C++
- 3 2 3
3 - 2 4
2 2 - 2
3 4 2 -

暴力

关于每组数据

我们可以dfs通过边权>=k的边

每经过一个点ans++;

注意不要记起点

C++

void dfs(int x)
{
	for(auto u: g[x])
	{
		if(u.z >= k)
		{
			dfs(u.x);
			ans++;
		}
	} 
} 

优化

我们可以先预处理任意两点的最小边权

并查集

先把每条边按边权排序

再把输入的问题按k排序

这样一旦有一条边在一前建好,在后面就不会删了

每次把边权比k大(可以等于)建边并合并 看和起点在同一个集合的结点个数

代码

C++
#include<bits/stdc++.h>
using namespace std;
struct Node
{
	int x, y, z;
	bool operator<(const Node &a) const
	{
		return z < a.z;
	}
};//存边
priority_queue<Node> s;
struct Pl
{
	int k, s, id;
	bool operator<(const Pl &a) const
	{
		return k > a.k;
	}
}p[100010];//存问题
int f[100010], ans[100010], size[100010];
//并查集模版
int find(int x)
{
	if(f[x] != x) 
	{
		int root = find(x);
		return f[x] = root;
	}
	return x;
}
void merge(int x, int y)
{
	x = find(x);
	y = find(y);
	if(x == y) return ;
	f[x] = y;
	size[y] += size[x];
}
int main()
{
	int n, k;
	cin >> n >> k;
	for(int i = 1; i <= n; i++)
	{
		f[i] = i;
		size[i] = i;
	}
	for(int i = 1; i < n; i++)
	{
		int x, y, z;
		cin >> x >> y >> z;
		s.push({x, y, z});
	}
	for(int i = 1; i <= k; i++)
	{
		cin >> p[i].k >> p[i].s;
		p[i].id = i;
	}
	sort(p + 1, p + k + 1);
	for(int i = 1; i <= k; i++)
	{
		while(!s.empty() && s.top().z >= p[i].k)
		{
			merge(s.top().x, s.top().y);
			s.pop();
          //合并
		}
		ans[p[i].id] = size[find(p[i].s)];
	}
	for(int i = 1; i <= k; i++)
	{
		cout << ans[i] << endl;
	}
}

完结

原文
存档评论1 条抓取于