比较重量

小明陪小红去看钻石,他们从一堆钻石中随机抽取两颗并比较她们的重量。这些钻石的重量各不相同。在他们们比较了一段时间后,它们看中了两颗钻石g1和g2。现在请你根据之前比较的信息判断这两颗钻石的哪颗更重。

给定两颗钻石的编号g1,g2,编号从1开始,同时给定关系数组vector,其中元素为一些二元组,第一个元素为一次比较中较重的钻石的编号,第二个元素为较轻的钻石的编号。最后给定之前的比较次数n。请返回这两颗钻石的关系,若g1更重返回1,g2更重返回-1,无法判断返回0。输入数据保证合法,不会有矛盾情况出现。

测试样例:
2,3,[[1,2],[2,4],[1,3],[4,3]],4

返回: 1

Solution
 import java.util.*;

 public class Cmp {
public int cmp(int g1, int g2, int[][] records, int n) {
Map<Integer,List<Integer>> map=new HashMap<Integer,List<Integer>>();
int max=0;
for(int[] pair:records){
if(!map.containsKey(pair[0])){
List<Integer> list=new ArrayList<Integer>();
list.add(pair[1]);
map.put(pair[0],list);
}
else map.get(pair[0]).add(pair[1]);
int temp=(pair[0]>pair[1])?pair[0]:pair[1];
max=(max>temp)?max:temp;
}
boolean[] isVisited1=new boolean[++max];
boolean[] isVisited2=new boolean[max];
if(isReachable(g1,g2,map,isVisited1)) return 1;
else if(isReachable(g2,g1,map,isVisited2)) return -1;
else return 0; }
private boolean isReachable(int now,int target,Map<Integer,List<Integer>> map,boolean[] isVisited){
if(now==target) return true;
isVisited[now]=true;
if(map.get(now)==null) return false;
int size=map.get(now).size();
for(int i=0;i<size;i++){
int next=map.get(now).get(i);
if(isVisited[next]) continue;
else if(isReachable(next,target,map,isVisited)) return true;
}
return false;
}
}

最新文章

  1. Delphi Json
  2. 在VBA中调用excel函数
  3. C#:调用webservice时提示对操作的回复消息正文进行反序列化时出错
  4. 【人在江湖飘,哪有不带刀】神器Jumony
  5. poj3694 缩点边双连通分量
  6. WordPress Kernel Theme ‘upload-handler.php’任意文件上传漏洞
  7. 调用ZoomEye API获取信息
  8. Spring DelegatingFilterProxy
  9. 结合JDK源码看设计模式——策略模式
  10. TF Multi-GPU single input queue
  11. web.xml中DispatcherServlet拦截器的配置详情
  12. git ssh 22 端口不可用时通过https 443 端口配置git ssh
  13. html一些标签在不同浏览器或者不同版本浏览器的注意事项
  14. build custom centos7
  15. C#反射基础理解1(转)
  16. MySQL配置优化需要避免的误区
  17. kafka集群安装,配置
  18. c语言学生信息管理系统-学习结构体
  19. web 应用响应乱码问题
  20. Ubuntu 12.04下LAMP环境搭建实录

热门文章

  1. eventloop &amp; actor模式 &amp; Java线程模型演进 &amp; Netty线程模型 总结
  2. win7 windows server 2008R2下 https SSL证书安装的搭配(搭配https ssl本地测试环境)
  3. APP自动化测试中Monkey和 MonkeyRunner
  4. features block
  5. KindEditor4.1.10,支持粘贴图片(转载!)
  6. 读javascript高级程序设计06-面向对象之继承
  7. iOS开发UI篇—ios应用数据存储方式(归档)
  8. pwnable.kr-fd
  9. 简单研究Android View绘制二 LayoutParams
  10. 简单使用SQLite 的增删改查