HYSBZ - 1050(旅行comf Java实现)

原题地址

解法:枚举每一条边,对于这条边,我们需要找到集合中和其值相差最小的最大边,这个集合是指与包括i边在内的ST联通集。对于这一要求,我们只需对所有的边进行从小到大的排序,那么从i边开始,一条条地加入并查集,一旦形成上述的联通集,立刻停止。

import java.io.*;
import java.util.*;
public class Main{
private static class edge{
int x,y,v;
}
private static class cmp implements Comparator<edge>{
@Override
public int compare(edge a,edge b){
return a.v<b.v?-1:1;
}
}
private static int fa[]=new int[505];
private static int Find(int x){
if(fa[x]==-1) return x;
return fa[x]=Find(fa[x]);
}
private static int gcd(int a,int b){
return b==0?a:gcd(b,a%b);
}
private static final int N=5000+5;
private static edge e[]=new edge[N];
public static void main(String[] args){
int n,m,s,t;
Scanner sc=new Scanner(new InputStreamReader(System.in));
n=sc.nextInt();m=sc.nextInt();
for(int i=0;i<m;i++){
e[i]=new edge();
e[i].x=sc.nextInt();
e[i].y=sc.nextInt();
e[i].v=sc.nextInt();
}
s=sc.nextInt();
t=sc.nextInt();
Arrays.sort(e,0,m,new cmp());
int x1=0,y1=0;
for(int i=0;i<m;i++){
int ma=-1;
Arrays.fill(fa,-1);
for (int j=i; j<m; j++){
int f1=Find(e[j].x),f2=Find(e[j].y);
if (f1==f2) continue;
fa[f1]=f2;
if (Find(s)==Find(t)){
ma=e[j].v;
break;
}
}
if (ma==-1&&i==0){
System.out.printf("IMPOSSIBLE\n");
System.exit(0);
}
if (ma==-1) break;
if (x1==0||x1*e[i].v>ma*y1){
x1=ma;y1=e[i].v;
}
}
int x=gcd(x1,y1);
if (x==y1) System.out.printf("%d\n",x1/y1);
else System.out.printf("%d/%d\n",x1/x,y1/x);
sc.close();
}
}

最新文章

  1. 【oracle】数据泵expdp与impdp
  2. 作业七:团队项目——Alpha版本冲刺阶段-10
  3. 程序员遇到BUG的解释
  4. Python小例子
  5. A sample of procedure in using
  6. CSS3详解:transform
  7. scala命令
  8. CALayer精讲
  9. ArcGIS 在地图上添加标注
  10. if和switch的区别,循环的for 和while的区别, 字符串常用的7种方法
  11. Swift LeetCode 目录 | Catalog
  12. C/C++ const
  13. C/C++(static)
  14. 【Git学习二】深入了解git checkout命令
  15. ASP.NET 前端Ajax获取数据并刷新
  16. 【Python全栈-后端开发】MySQL数据库-练习题
  17. Hanlp中使用纯JAVA实现CRF分词
  18. java 8 学习资料
  19. 关于lidroid xUtils 开源项目
  20. 如何搭建 LNMP环境

热门文章

  1. [Shell学习笔记] read命令从键盘或文件中获取标准输入(转载)
  2. Akka源码分析-Cluster-DistributedData
  3. golang——strconv包常用函数
  4. ssh&amp;amp;远程桌面连接工具finalshell
  5. Oracle11gR2设置连接数process与会话session值
  6. fiddler不同代理模式的区别
  7. Listview多种布局的使用
  8. The user specified as a definer (&#39;root&#39;@&#39;%&#39;) does not exist 解决方法
  9. ThinkPHP---thinkphp实用项
  10. 09C语言指针