hdu 1598 find the most comfortable road(并查集)
2024-08-27 17:45:14
题意:略
分析:多询问问题,利用并查集加速。类似于kruskal对MST的构建:枚举最小的边,逐渐将更大的边加入集合,当查询的点在同一个集合,那么当前最小值,就是所加的最后一条边与第一条只差。
注意:当枚举的最小边,把所有大边加入都不能使查询点(a,b)加入同一集合,那么终止枚举。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std; const int MAXN=;
const int INF=0x7fffffff; struct Edge{
int u,v,c;
Edge(){}
Edge(int _u,int _v,int _c):u(_u),v(_v),c(_c){}
}edge[MAXN]; int n,m;
int p[]; int cmp(Edge a,Edge b)
{
return a.c<b.c;
} void init()
{
for(int i=;i<=n;i++)
p[i]=i;
} int find(int x)
{
return p[x]==x?x:p[x]=find(p[x]);
} int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=;i<m;i++)
{
int u,v,c;
scanf("%d%d%d",&u,&v,&c);
edge[i]=Edge(u,v,c);
}
sort(edge,edge+m,cmp); int q;
scanf("%d",&q);
while(q--)
{
int mi=INF,a,b;
scanf("%d%d",&a,&b);
for(int i=;i<m;i++)
{
init();
int j;
for(j=i;j<m;j++)
{
int u=edge[j].u;
int v=edge[j].v;
int x=find(u);
int y=find(v);
if(x!=y)
p[x]=y;
if(find(a)==find(b))
break;
}
if(j==m)
break;
mi=min(mi,edge[j].c-edge[i].c);
}
if(mi==INF)
printf("-1\n");
else
printf("%d\n",mi);
}
}
return ;
}
最新文章
- css制作漂亮彩带导航条菜单
- Leetcode: Word Squares &;&; Summary: Another Important Implementation of Trie(Retrieve all the words with a given Prefix)
- CSS media queries
- 日历插件My97DatePicker的使用
- osgconv 批量转换
- iOS 开发小结
- MyBatis的Dao层注入SqlSession
- SaveFileDialog的用法
- jQuery实现的瀑布流效果, 向下滚动即时加载内容
- [AngularJS] Services, Factories, and Providers -- Service vs Factory
- OOP组合和继续的优缺点
- include file和include virtual的区别
- 利用iframe技巧获取訪问者qq
- ZeroMQ初探
- 九度OJ 1010 A +B
- java并发包下的并发工具类
- BI过程简述
- js绑定下拉框
- python appium笔记(二):元素定位
- Android WebView中软键盘会遮挡输入框相关问题
热门文章
- 「kuangbin带你飞」专题十五 数位DP
- luogu P1164 小A点菜
- SpringAop名词解释+基于xml的配置
- CocoaPods 错误 target overrides the `OTHER_LDFLAGS`...
- C语言基础之指针
- PHP安全相关的配置
- SQL Server Profiler和数据库引擎优化顾问
- 【IntellJ IDEA】idea的Terminal窗口中文乱码 解决方法
- nginx,wsgi,django的关系
- 利用【深度网络】高效提取feature