https://www.bnuoj.com/v3/contest_show.php?cid=9146#problem/F

【题意】

给定n个城市和m条带权边,q次查询,问某两个城市之间的所有路径中最大边和最小边的差值最小是多少?

【思路】

首先给所有的边从小到大排序,然后枚举最小边,向右遍历各条边:查找这条边的两个端点是否连通,不连通就加入并查集,并且更新q个查询的答案;连通的话不进行任何操作

【Accetped】

 #include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstring> using namespace std;
typedef long long ll;
typedef double db;
const int maxm=1e3+;
const int inf=0x3f3f3f3f;
struct sars
{
int x;
int y;
int w;
bool operator<(const sars& t)const
{
return w<t.w;
}
}node[maxm];
int n,m,q;
const int maxn=;
int stt[],ed[],ans[];
int fa[maxn];
int getfa(int x)
{
return x==fa[x]?x:fa[x]=getfa(fa[x]);
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(ans,inf,sizeof(ans));
for(int i=;i<m;i++)
{
scanf("%d%d%d",&node[i].x,&node[i].y,&node[i].w);
}
sort(node,node+m);
scanf("%d",&q);
for(int i=;i<q;i++)
{
scanf("%d%d",&stt[i],&ed[i]);
}
for(int i=;i<m;i++)
{
for(int k=;k<=n;k++)
{
fa[k]=k;
}
int mns=node[i].w;
for(int k=i;k<m;k++)
{
int u=node[k].x;
int v=node[k].y;
int w=node[k].w;
int x=getfa(u);
int y=getfa(v);
if(x!=y)
{
fa[x]=y;
for(int j=;j<q;j++)
{
if(getfa(stt[j])==getfa(ed[j]))
{
ans[j]=min(ans[j],w-mns);
}
}
}
}
}
for(int i=;i<q;i++)
{
if(ans[i]==inf)
{
printf("-1\n");
}
else
{
printf("%d\n",ans[i]);
}
}
}
return ;
}

最新文章

  1. BZOJ4583 : 购物
  2. struts2 CVE-2014-0050(DoS), CVE-2014-0094(ClassLoader manipulation) S2-20 DoS attacks and ClassLoader manipulation
  3. 利用pt-deadlock-logger监控死锁
  4. 遵循amd规范的require.js(适合浏览器端)
  5. window下安装nodejs
  6. 串行通讯之UARTLoopback
  7. 关于DatePicker控件在IsEnabled为False视觉效果没有明显辨识度的处理方法
  8. iOS 页面间传值 之 属性传值,代理传值
  9. JavaScript事件属性绑定带参数的函数
  10. iis7支持asp(访问页面,页面存在仍然提示404)
  11. 1702: [Usaco2007 Mar]Gold Balanced Lineup 平衡的队列
  12. WinForm的.Designer.cs代码内抛反射异常
  13. Android WebView的HTML中的select标签不起作用
  14. 报错Unexpected token u
  15. HashMap负载因子为什么是0.75
  16. Oracle常用函数——COALESCE
  17. python3 CERTIFICATE_VERIFY_FAILED错误 certificate verify failed
  18. USACO Arithmetic Progressions(暴力)
  19. codeforces#505--B Weakened Common Divisor
  20. SpringMVC 的 切面

热门文章

  1. apt-get的一些坑
  2. ubuntu中mysql安装失败
  3. LN : leetcode 684 Redundant Connection
  4. Android iconfont字体图标的使用
  5. Knockout-了解Observable与computed
  6. c++正则表达式模板库GRETA的使用
  7. const函数的使用
  8. Linux之常用Shell脚本总结
  9. win7下自动更新svn目录
  10. 客户端和服务器最多能发送和接收多少TCP连接数?