纪念一下自己的Coursera Princeton Algorithm的课程第一个assignment

本文主要是介绍纪念一下自己的Coursera Princeton Algorithm的课程第一个assignment,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

今天终于完成了第一个Union-Find的assignment,之前觉得特别的难,可是最后自己也搞定了。而且是100%满分。

自己后来plot了一下自己的分数,也许这就是学习曲线吧。刚开始不会,到后来中期显著提高,但是要到100%,那就要经历更多的波折,甚至是下降都有可能。最后才能达到100%满分。

我觉得最有用的还是下面这段源代码:

/*******************************************************************************  Compilation:  javac WeightedQuickUnionUF.java*  Execution:  java WeightedQuickUnionUF < input.txt*  Dependencies: StdIn.java StdOut.java*  Data files:   https://algs4.cs.princeton.edu/15uf/tinyUF.txt*                https://algs4.cs.princeton.edu/15uf/mediumUF.txt*                https://algs4.cs.princeton.edu/15uf/largeUF.txt**  Weighted quick-union (without path compression).*******************************************************************************/package edu.princeton.cs.algs4;/***  The {@code WeightedQuickUnionUF} class represents a <em>union–find data type</em>*  (also known as the <em>disjoint-sets data type</em>).*  It supports the <em>union</em> and <em>find</em> operations,*  along with a <em>connected</em> operation for determining whether*  two sites are in the same component and a <em>count</em> operation that*  returns the total number of components.*  <p>*  The union–find data type models connectivity among a set of <em>n</em>*  sites, named 0 through <em>n</em>–1.*  The <em>is-connected-to</em> relation must be an *  <em>equivalence relation</em>:*  <ul>*  <li> <em>Reflexive</em>: <em>p</em> is connected to <em>p</em>.*  <li> <em>Symmetric</em>: If <em>p</em> is connected to <em>q</em>,*       then <em>q</em> is connected to <em>p</em>.*  <li> <em>Transitive</em>: If <em>p</em> is connected to <em>q</em>*       and <em>q</em> is connected to <em>r</em>, then*       <em>p</em> is connected to <em>r</em>.*  </ul>*  <p>*  An equivalence relation partitions the sites into*  <em>equivalence classes</em> (or <em>components</em>). In this case,*  two sites are in the same component if and only if they are connected.*  Both sites and components are identified with integers between 0 and*  <em>n</em>–1. *  Initially, there are <em>n</em> components, with each site in its*  own component.  The <em>component identifier</em> of a component*  (also known as the <em>root</em>, <em>canonical element</em>, <em>leader</em>,*  or <em>set representative</em>) is one of the sites in the component:*  two sites have the same component identifier if and only if they are*  in the same component.*  <ul>*  <li><em>union</em>(<em>p</em>, <em>q</em>) adds a*      connection between the two sites <em>p</em> and <em>q</em>.*      If <em>p</em> and <em>q</em> are in different components,*      then it replaces*      these two components with a new component that is the union of*      the two.*  <li><em>find</em>(<em>p</em>) returns the component*      identifier of the component containing <em>p</em>.*  <li><em>connected</em>(<em>p</em>, <em>q</em>)*      returns true if both <em>p</em> and <em>q</em>*      are in the same component, and false otherwise.*  <li><em>count</em>() returns the number of components.*  </ul>*  <p>*  The component identifier of a component can change*  only when the component itself changes during a call to*  <em>union</em>—it cannot change during a call*  to <em>find</em>, <em>connected</em>, or <em>count</em>.*  <p>*  This implementation uses weighted quick union by size (without path compression).*  Initializing a data structure with <em>n</em> sites takes linear time.*  Afterwards, the <em>union</em>, <em>find</em>, and <em>connected</em>*  operations  take logarithmic time (in the worst case) and the*  <em>count</em> operation takes constant time.*  For alternate implementations of the same API, see*  {@link UF}, {@link QuickFindUF}, and {@link QuickUnionUF}.**  <p>*  For additional documentation, see <a href="https://algs4.cs.princeton.edu/15uf">Section 1.5</a> of*  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.**  @author Robert Sedgewick*  @author Kevin Wayne*/
public class WeightedQuickUnionUF {private int[] parent;   // parent[i] = parent of iprivate int[] size;     // size[i] = number of sites in subtree rooted at iprivate int count;      // number of components/*** Initializes an empty union–find data structure with {@code n} sites* {@code 0} through {@code n-1}. Each site is initially in its own * component.** @param  n the number of sites* @throws IllegalArgumentException if {@code n < 0}*/public WeightedQuickUnionUF(int n) {count = n;parent = new int[n];size = new int[n];for (int i = 0; i < n; i++) {parent[i] = i;size[i] = 1;}}/*** Returns the number of components.** @return the number of components (between {@code 1} and {@code n})*/public int count() {return count;}/*** Returns the component identifier for the component containing site {@code p}.** @param  p the integer representing one object* @return the component identifier for the component containing site {@code p}* @throws IllegalArgumentException unless {@code 0 <= p < n}*/public int find(int p) {validate(p);while (p != parent[p])p = parent[p];return p;}// validate that p is a valid indexprivate void validate(int p) {int n = parent.length;if (p < 0 || p >= n) {throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1));  }}/*** Returns true if the the two sites are in the same component.** @param  p the integer representing one site* @param  q the integer representing the other site* @return {@code true} if the two sites {@code p} and {@code q} are in the same component;*         {@code false} otherwise* @throws IllegalArgumentException unless*         both {@code 0 <= p < n} and {@code 0 <= q < n}*/public boolean connected(int p, int q) {return find(p) == find(q);}/*** Merges the component containing site {@code p} with the * the component containing site {@code q}.** @param  p the integer representing one site* @param  q the integer representing the other site* @throws IllegalArgumentException unless*         both {@code 0 <= p < n} and {@code 0 <= q < n}*/public void union(int p, int q) {int rootP = find(p);int rootQ = find(q);if (rootP == rootQ) return;// make smaller root point to larger oneif (size[rootP] < size[rootQ]) {parent[rootP] = rootQ;size[rootQ] += size[rootP];}else {parent[rootQ] = rootP;size[rootP] += size[rootQ];}count--;}/*** Reads in a sequence of pairs of integers (between 0 and n-1) from standard input, * where each integer represents some object;* if the sites are in different components, merge the two components* and print the pair to standard output.** @param args the command-line arguments*/public static void main(String[] args) {int n = StdIn.readInt();WeightedQuickUnionUF uf = new WeightedQuickUnionUF(n);while (!StdIn.isEmpty()) {int p = StdIn.readInt();int q = StdIn.readInt();if (uf.connected(p, q)) continue;uf.union(p, q);StdOut.println(p + " " + q);}StdOut.println(uf.count() + " components");}}/*******************************************************************************  Copyright 2002-2018, Robert Sedgewick and Kevin Wayne.**  This file is part of algs4.jar, which accompanies the textbook**      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,*      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.*      http://algs4.cs.princeton.edu***  algs4.jar is free software: you can redistribute it and/or modify*  it under the terms of the GNU General Public License as published by*  the Free Software Foundation, either version 3 of the License, or*  (at your option) any later version.**  algs4.jar is distributed in the hope that it will be useful,*  but WITHOUT ANY WARRANTY; without even the implied warranty of*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the*  GNU General Public License for more details.**  You should have received a copy of the GNU General Public License*  along with algs4.jar.  If not, see http://www.gnu.org/licenses.******************************************************************************/

 

这篇关于纪念一下自己的Coursera Princeton Algorithm的课程第一个assignment的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1136325

相关文章

好题——hdu2522(小数问题:求1/n的第一个循环节)

好喜欢这题,第一次做小数问题,一开始真心没思路,然后参考了网上的一些资料。 知识点***********************************无限不循环小数即无理数,不能写作两整数之比*****************************(一开始没想到,小学没学好) 此题1/n肯定是一个有限循环小数,了解这些后就能做此题了。 按照除法的机制,用一个函数表示出来就可以了,代码如下

Spring Roo 实站( 一 )部署安装 第一个示例程序

转自:http://blog.csdn.net/jun55xiu/article/details/9380213 一:安装 注:可以参与官网spring-roo: static.springsource.org/spring-roo/reference/html/intro.html#intro-exploring-sampleROO_OPTS http://stati

【详细介绍一下GEE】

GEE(Google Earth Engine)是一个强大的云计算平台,它允许用户处理和分析大规模的地球科学数据集,如卫星图像、气候模型输出等。以下是对GEE用法的详细介绍: 一、平台访问与账户设置 访问GEE平台: 用户可以通过访问Google Earth Engine的官方网站来开始使用GEE。 创建账户: 用户需要注册并登录Google账户,然后申请访问GEE平台。申请过程可能需要提

使用gradle做第一个java项目

涉及到的任务如下: assemble任务会编译程序中的源代码,并打包生成Jar文件,这个任务不执行单元测试。 Total time: 5.581 secs E:\workspace\Test>gradle assemble :compileJava :processResources UP-TO-DATE :classes :findMainClass :jar :b

《数字图像处理(面向新工科的电工电子信息基础课程系列教材)》P98

更改为 差分的数学表达式从泰勒级数展开式可得: 后悔没听廖老师的。 禹晶、肖创柏、廖庆敏《数字图像处理(面向新工科的电工电子信息基础课程系列教材)》 禹晶、肖创柏、廖庆敏《数字图像处理》资源二维码

vue2实践:第一个非正规的自定义组件-动态表单对话框

前言 vue一个很重要的概念就是组件,作为一个没有经历过前几代前端开发的我来说,不太能理解它所带来的“进步”,但是,将它与后端c++、java类比,我感觉,组件就像是这些语言中的类和对象的概念,通过封装好的组件(类),可以通过挂载的方式,非常方便的调用其提供的功能,而不必重新写一遍实现逻辑。 我们常用的element UI就是由饿了么所提供的组件库,但是在项目开发中,我们可能还需要额外地定义一

SpringMVC的第一个案例 Helloword 步骤

第一步:web.xml配置 <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocati

我的第一次份实习工作-iOS实习生-第一个月

实习时间:2015-08-20 到 2015-12-25  实习公司;福建天棣互联有限公司 实习岗位:iOS开发实习生 第一个月: 第一天来公司,前台报道后,人资带我去我工作的地方。到了那,就由一个组长带我,当时还没有我的办公桌,组长在第三排给我找了一个位置,擦了下桌子,把旁边的准备的电脑帮我装了下,因为学的是iOS,实习生就只能用黑苹果了,这是我实习用的电脑。 帮我装了一下电脑后,开机

从零开始:打造你的第一个餐厅点餐小程序

目录 1 为什么选择点餐小程序2 会有哪些功能2.1 顾客端2.2 服务员端2.3 后厨端2.4 收银端2.5 管理员(老板)端 3 开发工具选择4 你将获得什么让我们开始吧 最近,有不少粉丝咨询,有没有系统的低代码学习教程呀?为啥你的教程有的刚看的提起兴趣,怎么突然就中断了。有没有系统的视频学习教程呀,你是不是还有压箱底的好宝贝,没开放给我们看呀。 还真不是,压箱底的好宝贝已

2015多校联合训练第一场Assignment(hdu5289)三种解法

题目大意:给出一个数列,问其中存在多少连续子序列,子序列的最大值-最小值< k 这题有三种解法: 1:单调队列,时间复杂度O(n) 2:RMQ+二分,时间复杂度O(nlogn) 3:RMQ+贪心,时间复杂度O(nlogn) 一:RMQ+二分 RMQ维护最大值,最小值,枚举左端点i,二分找出最远的符合的右端点j,答案就是ans += j - i+1;(手推一下就知道) 比如1 2 3