G. Path Queries

topic

Meaning of the questions:

    Given a weighted trees, m visits, each entry a qi. Required output all points (u, v), the path between them is less than the maximum value authorized to access.
     1 n , m 2 1 0 5 , 1 q i 2 1 0 5 1≤n,m≤2⋅10^5,1≤q_i≤2⋅10^5

analysis:

    If you are re-contribution of each visit, then obviously it will burst time. In fact, we can access offline, from small to large, then edge from small to large. So that we can gradually build up a tree based on continuous access. For a side that can be added, its contribution to the answer is the number of points multiplied by two Unicom blocks in which it is connected. In order to maintain the number of blocks communication midpoint, we can use the disjoint-set.

#include <iostream>
#include <algorithm>
using namespace std;

typedef long long ll;

int parent[200005],size[200005];

struct edge{
	int x,y,val;
	bool operator<(const edge&e)const
	{
		return val < e.val;
	}
}a[200005];

struct query{
	int id,val;
	bool operator<(const query&q)const
	{
		return val < q.val;
	}
}q[200005];

ll res[200005];

int find(int p)
{
	if( p == parent[p] ) return p;
	return parent[p] = find(parent[p]);
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int n,m;
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
	{
		parent[i] = i;
		size[i] = 1;
	}
	for (int i = 1; i < n; i++)
	{
		cin >> a[i].x >> a[i].y >> a[i].val;
	} 
	sort(a+1,a+n);
	for (int i = 1; i <= m; i++)
	{
		cin >> q[i].val;
		q[i].id = i;
	}
	sort(q+1,q+1+m);
	int index = 1;
	ll ans = 0;
	for (int i = 1; i <= m; i++)
	{
		while( index < n && a[index].val <= q[i].val )
		{
			int x = a[index].x;
			int y = a[index].y;
			int rootx = find(x);
			int rooty = find(y);
			ans += (ll)size[rootx] * size[rooty];
			size[rootx] += size[rooty];
			parent[rooty] = rootx; 
			index ++;
		}
		res[q[i].id] = ans;
	}
	for (int i = 1; i <= m; i++)
	{
		cout << res[i];
		if( i == m ) cout << '\n';
		else cout << ' ';
	}
	return 0;
}

Published 132 original articles · won praise 6 · views 7929

Guess you like

Origin blog.csdn.net/weixin_44316314/article/details/104855048