题意:略

分析:多询问问题,利用并查集加速。类似于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 ;
}

最新文章

  1. css制作漂亮彩带导航条菜单
  2. Leetcode: Word Squares &amp;&amp; Summary: Another Important Implementation of Trie(Retrieve all the words with a given Prefix)
  3. CSS media queries
  4. 日历插件My97DatePicker的使用
  5. osgconv 批量转换
  6. iOS 开发小结
  7. MyBatis的Dao层注入SqlSession
  8. SaveFileDialog的用法
  9. jQuery实现的瀑布流效果, 向下滚动即时加载内容
  10. [AngularJS] Services, Factories, and Providers -- Service vs Factory
  11. OOP组合和继续的优缺点
  12. include file和include virtual的区别
  13. 利用iframe技巧获取訪问者qq
  14. ZeroMQ初探
  15. 九度OJ 1010 A +B
  16. java并发包下的并发工具类
  17. BI过程简述
  18. js绑定下拉框
  19. python appium笔记(二):元素定位
  20. Android WebView中软键盘会遮挡输入框相关问题

热门文章

  1. 「kuangbin带你飞」专题十五 数位DP
  2. luogu P1164 小A点菜
  3. SpringAop名词解释+基于xml的配置
  4. CocoaPods 错误 target overrides the `OTHER_LDFLAGS`...
  5. C语言基础之指针
  6. PHP安全相关的配置
  7. SQL Server Profiler和数据库引擎优化顾问
  8. 【IntellJ IDEA】idea的Terminal窗口中文乱码 解决方法
  9. nginx,wsgi,django的关系
  10. 利用【深度网络】高效提取feature