hdu-3938 Portal 离线最小生成树

题目链接

题意描述:简单的讲就是,给你一张无向图,求有多少条路径使得路径上的花费小于L,这里路径上的花费是这样规定的,a、b两点之间的多条路径中的最长的边最小值!


#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef __int64 LL;
const int maxn = 50005;
const int inf = 2000000001;
int n,m,q;
int p[maxn],r[maxn];
struct node
{
	int u,v,w;
}edge[maxn];
struct Node
{
	int id,len,ans;
}que[maxn];
bool cmp( node a,node b )
{
	return a.w < b.w;
}
bool cmpq( Node a,Node b )
{
	return a.len < b.len;
}
bool cmpid( Node a,Node b )
{
	return a.id < b.id;
}
int find( int x )
{
	return x == p[x]?x:p[x] = find( p[x] );
}
void init()
{
	for( int i = 1; i <= n; i ++ )
	{
		p[i] = i;
		r[i] = 1;
	}
}
int main()
{
    #ifndef ONLINE_JUDGE     
	freopen("data.txt","r",stdin);     
	#endif 
	int u,v,w;
	while( scanf("%d%d%d",&n,&m,&q) != EOF )
	{
		init();
		for( int i = 0; i < m; i ++ )
		{
			scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
		}
		for( int i = 0; i < q; i ++ )
		{
			scanf("%d",&que[i].len);
			que[i].id = i;
			que[i].ans = 0;
		}
		sort( edge,edge+m,cmp );
		sort( que,que+q,cmpq );
		int cnt = 0;
		for( int i = 0; i < q; i ++ )
		{
			while( edge[cnt].w <= que[i].len && cnt < m )
			{
				int fx = find( edge[cnt].u );
				int fy = find( edge[cnt].v );
				if( fx != fy )
				{
					que[i].ans += r[fx] * r[fy];
					if( p[fx] < p[fy] )
					{
						p[fy] = fx;
						r[fx] += r[fy];
					}
					else
					{
						p[fx] = fy;
						r[fy] += r[fx];
					}
				}
				cnt ++;
			}
			if( i > 0 )
				que[i].ans += que[i-1].ans;
		}
		sort( que,que+q,cmpid );
		for( int i = 0; i < q; i ++ )
		{
			printf("%d\n",que[i].ans);
		}
	}
	return 0;
}


你可能感兴趣的:(图论-最小生成树)