这周的作业可谓是一波三折,但是收获了不少,熟悉了广度优先搜索还有符号图的建立。此外还知道了Integer.MAX_VALUE。

SAP:

求v和w的大概思路是对v和w分别广度优先搜索,然后遍历图中每一个顶点,如果v和w都可以到达一个顶点,就计算v和w到这一顶点的距离和,最后求出最短的距离以及对应的顶点便是所求length和ancestor。

至于Iterable<Integer> v和Iterable<Integer> w,开始我是求v中每一个顶点和w中的每一个顶点的距离,然后求出最短距离,但提交后时间测试通不过。参考了其他人的一些博客后发现可以遍历一次完成对v或w的广度优先搜索,于是自己写了一个BFS类。然而这次提交出现了OperationCountLimitExceededException,最后检查了半天才发现bfs时丢了一句   ' if(!marked[w]) '。。。后来发现官方提供的BreadthFirstDirectedPaths类可以完成Iterable<Integer> v的广度优先搜索,于是干脆直接调用这个。

但是提交后还是有问题。。。对于没有共同祖先的情况判断不正确,不能返回-1,检查了半天发现每次求length或ancestor都应该在前面加上 anc = -1; 否则这次求返回的是上次的anc。

  1. import edu.princeton.cs.algs4.*;
  2. import edu.princeton.cs.algs4.In;
  3.  
  4. public class SAP {
  5. private Digraph G;
  6. private int anc = -1;
  7. // constructor takes a digraph (not necessarily a DAG)
  8. public SAP(Digraph G) {
  9. if(G == null) throw new IllegalArgumentException();
  10. this.G = new Digraph(G);
  11. }
  12.  
  13. // length of shortest ancestral path between v and w; -1 if no such path
  14. public int length(int v, int w) {
  15. if(v < 0 || v > G.V() - 1 || w < 0 || w > G.V() - 1)
  16. throw new IllegalArgumentException();
  17. anc = -1;
  18.  
  19. BreadthFirstDirectedPaths bv = new BreadthFirstDirectedPaths(G, v);
  20. BreadthFirstDirectedPaths bw = new BreadthFirstDirectedPaths(G, w);
  21.  
  22. int minLength = Integer.MAX_VALUE;
  23.  
  24. for(int i = 0; i < G.V(); i++) {
  25. if(bv.hasPathTo(i) && bw.hasPathTo(i)) {
  26. int l = bv.distTo(i) + bw.distTo(i);
  27. if(l < minLength) {
  28. minLength = l;
  29. anc = i;
  30. }
  31. }
  32. }
  33.  
  34. if(minLength == Integer.MAX_VALUE) return -1;
  35. else return minLength;
  36.  
  37. }
  38.  
  39. // a common ancestor of v and w that participates in a shortest ancestral path; -1 if no such path
  40. public int ancestor(int v, int w) {
  41. length(v, w);
  42. return anc;
  43. }
  44.  
  45. // length of shortest ancestral path between any vertex in v and any vertex in w; -1 if no such path
  46. public int length(Iterable<Integer> v, Iterable<Integer> w) {
  47. if(v == null || w == null)
  48. throw new IllegalArgumentException();
  49. anc = -1;
  50.  
  51. for(int i : v) {
  52. if(i < 0 || i > G.V() - 1)
  53. throw new IllegalArgumentException();
  54. }
  55. for(int i : w) {
  56. if(i < 0 || i > G.V() - 1)
  57. throw new IllegalArgumentException();
  58. }
  59.  
  60. BreadthFirstDirectedPaths bv = new BreadthFirstDirectedPaths(G, v);
  61. BreadthFirstDirectedPaths bw = new BreadthFirstDirectedPaths(G, w);
  62.  
  63. int minLength = Integer.MAX_VALUE;
  64.  
  65. for(int i = 0; i < G.V(); i++) {
  66. if(bv.hasPathTo(i) && bw.hasPathTo(i)) {
  67. int l = bv.distTo(i) + bw.distTo(i);
  68. if(l < minLength) {
  69. minLength = l;
  70. anc = i;
  71. }
  72. }
  73. }
  74.  
  75. if(minLength == Integer.MAX_VALUE) return -1;
  76. else return minLength;
  77. }
  78.  
  79. // a common ancestor that participates in shortest ancestral path; -1 if no such path
  80. public int ancestor(Iterable<Integer> v, Iterable<Integer> w) {
  81. length(v, w);
  82. return anc;
  83. }
  84.  
  85. // do unit testing of this class
  86. public static void main(String[] args) {
  87.  
  88. }
  89. }

WordNet:

wordnet涉及到符号图的问题,开始用ST<String, Integer>来完成noun到id的索引,后来发现一个noun可能对应多个id,于是改为ST<String, Bag<Integer>>。

需要检查有向图是否合格:1.不能有环。通过类DirectedCycle完成。 2.只能有一个root。经参考别人的博客发现一个很巧妙的方法,如果一个顶点是根,那么它不指向其它顶点,所以它不会出现在hypernyms每行的第一个id。

方法sap需要通过id得到noun,用数组的话不能提前知道数组大小,于是参考网上用ArrayList<String>完成id到noun的索引。

  1. import edu.princeton.cs.algs4.*;
  2. import java.util.ArrayList;
  3.  
  4. public class WordNet {
  5. private ST<String, Bag<Integer>> st;
  6. private ArrayList<String> idList;
  7. private Digraph G;
  8.  
  9. // constructor takes the name of the two input files
  10. public WordNet(String synsets, String hypernyms) {
  11. if(synsets == null || hypernyms == null) throw new IllegalArgumentException();
  12.  
  13. st = new ST<String, Bag<Integer>>();
  14. idList = new ArrayList<String>();
  15.  
  16. int count = 0;
  17. In in1 = new In(synsets);
  18. while(in1.hasNextLine()) {
  19. String[] a = in1.readLine().split(",");
  20. String[] a2 = a[1].split(" ");
  21.  
  22. for(int i = 0; i < a2.length; i++) {
  23. if(st.contains(a2[i])) st.get(a2[i]).add(Integer.parseInt(a[0]));
  24. else {
  25. Bag<Integer> b = new Bag<Integer>();
  26. b.add(Integer.parseInt(a[0]));
  27. st.put(a2[i], b);
  28. }
  29. }
  30. count++;
  31. idList.add(a[1]);
  32. }
  33.  
  34. G = new Digraph(count);
  35. In in2 = new In(hypernyms);
  36. boolean[] isNotRoot = new boolean[count];
  37. int rootNumber = 0;
  38.  
  39. while(in2.hasNextLine()) {
  40. String[] a = in2.readLine().split(",");
  41. isNotRoot[Integer.parseInt(a[0])] = true;
  42. for(int i = 1; i < a.length; i++)
  43. G.addEdge(Integer.parseInt(a[0]), Integer.parseInt(a[i]));
  44. }
  45.  
  46. for(int i = 0; i < count; i++) {
  47. if(!isNotRoot[i]) rootNumber++;
  48. }
  49. DirectedCycle d = new DirectedCycle(G);
  50. if(rootNumber > 1 || d.hasCycle()) throw new IllegalArgumentException();
  51. }
  52.  
  53. // returns all WordNet nouns
  54. public Iterable<String> nouns() {
  55. return st.keys();
  56. }
  57.  
  58. // is the word a WordNet noun?
  59. public boolean isNoun(String word) {
  60. if(word == null) throw new IllegalArgumentException();
  61. return st.contains(word);
  62. }
  63.  
  64. // distance between nounA and nounB (defined below)
  65. public int distance(String nounA, String nounB) {
  66. if(nounA == null || nounB == null || !isNoun(nounA) || !isNoun(nounB))
  67. throw new IllegalArgumentException();
  68. SAP s = new SAP(G);
  69. Bag<Integer> ida = st.get(nounA);
  70. Bag<Integer> idb = st.get(nounB);
  71.  
  72. return s.length(ida, idb);
  73. }
  74.  
  75. // a synset (second field of synsets.txt) that is the common ancestor of nounA and nounB
  76. // in a shortest ancestral path (defined below)
  77. public String sap(String nounA, String nounB) {
  78. if(nounA == null || nounB == null || !isNoun(nounA) || !isNoun(nounB))
  79. throw new IllegalArgumentException();
  80. SAP s = new SAP(G);
  81. Bag<Integer> ida = st.get(nounA);
  82. Bag<Integer> idb = st.get(nounB);
  83.  
  84. int root = s.ancestor(ida, idb);
  85. return idList.get(root);
  86. }
  87.  
  88. // do unit testing of this class
  89. public static void main(String[] args) {
  90.  
  91. }
  92. }

Outcast:

  1. public class Outcast {
  2. private WordNet wordnet;
  3.  
  4. // constructor takes a WordNet object
  5. public Outcast(WordNet wordnet) {
  6. this.wordnet = wordnet;
  7. }
  8. // given an array of WordNet nouns, return an outcast
  9. public String outcast(String[] nouns) {
  10. int length = nouns.length;
  11. int[][] distance = new int[length][length];
  12.  
  13. for(int i = 0; i < length; i++) {
  14. for(int j = i; j < length; j++) {
  15. distance[i][j] = wordnet.distance(nouns[i], nouns[j]);
  16. }
  17. }
  18.  
  19. int maxDistance = 0;
  20. int sum = 0;
  21. int num = 0;
  22. for(int i = 0; i < nouns.length; i++) {
  23. sum = 0;
  24. for(int j = 0; j < nouns.length; j++) {
  25. if(i < j)
  26. sum += distance[i][j];
  27. else
  28. sum += distance[j][i];
  29. }
  30.  
  31. if(sum > maxDistance) {
  32. maxDistance = sum;
  33. num = i;
  34. }
  35. }
  36.  
  37. return nouns[num];
  38. }
  39. // see test client below
  40. public static void main(String[] args) {
  41. }
  42. }

coursera 算法二 week 1 wordnet的更多相关文章

  1. Coursera 算法二 week2 Seam Carving

    这周作业设计到的算法是有向无环图的最短路径算法,只需要按照顶点的拓扑顺序去放松顶点即可.而在这个题目中拓扑顺序就是按照行的顺序或列的顺序. 用到的数据结构为一个二维数组picture同来存储每个像素的 ...

  2. Coursera 算法二 week 5 BurrowsWheeler

    本打算周末完成这次作业,但没想到遇到了hard deadline,刚开始看不懂题意,后来发现算法4书上有个类似的问题,才理解了题意.最后晚上加班,上课加班,还好在11:35也就是课程结束前25分钟完成 ...

  3. Coursera 算法二 week 3 Baseball Elimination

    这周的作业不需要自己写算法,只需要调用库函数就行,但是有些难以理解,因此用了不少时间. import edu.princeton.cs.algs4.FlowEdge; import edu.princ ...

  4. Coursera 算法二 week 4 Boggle

    这次的作业主要用到了单词查找树和深度优先搜索. 1.在深度优先搜索中,在当前层的递归调用前,将marked数组标记为true.当递归调用返回到当前层时,应将marked数组标记为false.这样既可以 ...

  5. TensorFlow 入门之手写识别(MNIST) softmax算法 二

    TensorFlow 入门之手写识别(MNIST) softmax算法 二 MNIST Fly softmax回归 softmax回归算法 TensorFlow实现softmax softmax回归算 ...

  6. 分布式共识算法 (二) Paxos算法

    系列目录 分布式共识算法 (一) 背景 分布式共识算法 (二) Paxos算法 分布式共识算法 (三) Raft算法 分布式共识算法 (四) BTF算法 一.背景 1.1 命名 Paxos,最早是Le ...

  7. Floyd算法(二)之 C++详解

    本章是弗洛伊德算法的C++实现. 目录 1. 弗洛伊德算法介绍 2. 弗洛伊德算法图解 3. 弗洛伊德算法的代码说明 4. 弗洛伊德算法的源码 转载请注明出处:http://www.cnblogs.c ...

  8. Dijkstra算法(二)之 C++详解

    本章是迪杰斯特拉算法的C++实现. 目录 1. 迪杰斯特拉算法介绍 2. 迪杰斯特拉算法图解 3. 迪杰斯特拉算法的代码说明 4. 迪杰斯特拉算法的源码 转载请注明出处:http://www.cnbl ...

  9. Prim算法(二)之 C++详解

    本章是普里姆算法的C++实现. 目录 1. 普里姆算法介绍 2. 普里姆算法图解 3. 普里姆算法的代码说明 4. 普里姆算法的源码 转载请注明出处:http://www.cnblogs.com/sk ...

随机推荐

  1. Unix Tutorial Eight

    1.UNIX 变量 变量是在运行时将信息从shell传递到程序的一种方式.程序在特定的变量中查找“在环境中”,如果发现它们将使用存储的值.有些是由系统设置的,另一些是由你设置的,还有一些是由shell ...

  2. [Xcode 实际操作]三、视图控制器-(8)在Storyboard中设置初始化视图控制器

    目录:[Swift]Xcode实际操作 本文将演示如何设置故事板的初始视图控制器. 打开自动生成的默认故事板[Main.storyboard] 在打开的故事板中,系统已经生成了一个空白的视图控制器. ...

  3. PAT天梯赛L2-008 最长对称字符串

    题目链接:点击打开链接 对给定的字符串,本题要求你输出最长对称子串的长度.例如,给定"Is PAT&TAP symmetric?",最长对称子串为"s PAT&a ...

  4. PAT天梯赛L2-007 家庭房产

    题目链接:点击打开链接 给定每个人的家庭成员和其自己名下的房产,请你统计出每个家庭的人口数.人均房产面积及房产套数. 输入格式: 输入第一行给出一个正整数N(<=1000),随后N行,每行按下列 ...

  5. CPU使用情况检测

    改编自:https://blog.csdn.net/Yan_Chou/article/details/80456995 检测命令整理: dd iotop df top psiostatvmstatne ...

  6. Ubuntu14.04升级到Ubuntu16.04

    Ubuntu14.04升级到Ubuntu16.04 1.查看目前版本 lsb_release -a 2.执行更新命令 apt-get update && apt-get dist-up ...

  7. Java中keytool管理证书

    1.创建证书库以及第一个证书 keytool -genkeypair -alias "wangpass" -keyalg "RSA" -keystore &qu ...

  8. 平衡树合集(Treap,Splay,替罪羊,FHQ Treap)

    今天翻了翻其他大佬的博客,发现自己有些...颓废... 有必要洗心革面,好好学习 序:正常的BST有可能退化,成为链,大大降低效率,所以有很多方法来保持左右size的平衡,本文将简单介绍Treap,S ...

  9. codeforces C. Vasya And The Mushrooms (思维+模拟)

    题意:给定一个2*n的矩形方格,每个格子有一个权值,从(0,0)开始出发,要求遍历完整个网格(不能重复走一个格子),求最大权值和,(权值和是按照step*w累加,step步数从0开始). 转载: 题解 ...

  10. linux查看硬盘空间,删除大文件

    df -Phdu -h --max-depth=1du -sh /u02/weblogic/user_projects/domains/logsdu -sh /u02/mysqlfind / -siz ...