Given a family tree, find out if two people are blood related

Given a family tree for a few generations for the entire population and two people write a routine that will find out if they are blood related. Siblings are blood related since they have the same parents. Cousins are blood related since one of their parents have the same parents etc. Design the data structure first and then write the routine.

https://www.careercup.com/question?id=4812957531766784

解法:G家,we can use DFS or BFS, DFS is generally a bit easier to implement.

If they have a common ancestor.

Data structure: Graph, becausd two parents. Store parents in an array or list rather than having a separate pointer for the father and mother.

DFS/BFS startig from 1 person is not ideal. BFS/Iterative Deepening for common ancestor from each person, as don‘t process unnecessary children.

Lots of ways to determine a common ancestor. pure recursion, recursively compute the ancestor set of both people and check intersection, iterative deepening to build up the sets.

Java:

For 2 persons to be blood related, perform a Breadth First Traversal with the person as root and the parents as child nodes and store in a ArrayList.
Then for both the persons search is there is a common parent in the ArrayList.
If common parent found then, the persons are related, else not related.

The data structure to store the generation tree will have nodes defined as

public class Person {
	String name;
	ArrayList<Person> children = null;
	Person parent1;
	Person parent2;

	public Person(String personName, Person personParent1, Person personParent2) {
		name = personName;
		children = new ArrayList<Person>();
		parent1 = personParent1;
		parent2 = personParent2;
	}
	public Person getParent() { return parent; }
}

Java:

public class Person {
  Person[] parents;
}

// naming for cousins is: n th cousin m times removed
// where n is the min generations to a common ancestor and m is the number of generations difference between the 2 cousins
// so this is going to be O((2^n+m)+2) which is still more efficient than dfs assuming the num generations in the population is > n+m
public boolean bloodRelated(Person p1, Person p2) {
  // simple search would go down p1‘s children/grandchildren/etc and see if we find p2
  // then vice versa
  // then worry about cousin style relationships
  // here we‘d go up the parent tree on both until we found a common node (or ran out of data)

  // we could take this last approach anyway and it would get us a parent-child match too
  Set<Person> p1Ancestors = new HashSet<Person>();
  Set<Person> p2Ancestors = new HashSet<Person>();

  // so ideally here we‘re going to do BFS, but we‘re going to do 2 at once to try to minimise the depth we have to go
  List<Person> p1Discovered = new LinkedList<Person>();
  p1Discovered.add(p1);
  List<Person> p2Discovered = new LinkedList<Person>();
  p2Discovered.add(p2);

  while (!p1Discovered.isEmpty() || !p2Discovered.isEmpty()) {
    Person nextP1 = p1Discovered.remove(0);
    if (nextP1 != null) {
      if (p2Ancestors.contains(nextP1)) {
        return true;
      }

      for (Person parent : nextP1.parents) {
        p1Discovered.add(parent);
      }
      p1Ancestors.add(nextP1);
    }

    Person nextP2 = p2Discovered.remove(0);
    if (nextP2 != null) {
      if (p1Ancestors.contains(nextP2)) {
        return true;
      }

      for (Person parent : nextP2.parents) {
        p2Discovered.add(parent);
      }
      p2Ancestors.add(nextP2);
    }
  }
  return false;
}

  

原文地址:https://www.cnblogs.com/lightwindy/p/9808253.html

时间: 2024-11-10 13:24:30

Given a family tree, find out if two people are blood related的相关文章

openerp学习笔记 context 的应用

1.在Action中定义,context用于传递搜索条件和分组条件,在搜索视图中默认显示: 示例代码: <record model="ir.actions.act_window" id="open_company_allocation"> <field name="name">Leaves Summary</field> <field name="res_model">hr.ho

easyui js取消选中 Tree 指定节点

取消所有选中 var rootNodes = treeObject.tree('getRoots'); for ( var i = 0; i < rootNodes.length; i++) { var node = treeObject.tree('find', rootNodes[i].id); treeObject.tree('uncheck', node.target); }

Maximum Depth of Binary Tree

这道题为简单题 题目: Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 思路: 我是用递归做的,当然也可以用深搜和广搜,递归的话就是比较左右子树的深度然后返回 代码: 1 # Definition for a binary tre

538. Convert BST to Greater Tree 二叉搜索树转换为更大树

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. Example: Input: The root of a Binary Search Tree like thi

SPOJ375 Query on a tree

https://vjudge.net/problem/SPOJ-QTREE 题意: 一棵树,每条边有个权值 两种操作 一个修改每条边权值 一个询问两点之间这一条链的最大边权 点数<=10000 多组测试数据,case<=20 Example Input: 1 3 1 2 1 2 3 2 QUERY 1 2 CHANGE 1 3 QUERY 1 2 DONE Output: 1 3 #include<cstdio> #include<iostream> #include&

POJ 1741 Tree(树的点分治,入门题)

Tree Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 21357   Accepted: 7006 Description Give a tree with n vertices,each edge has a length(positive integer less than 1001).Define dist(u,v)=The min distance between node u and v.Give an in

命令-tree

tree命令 tree - list contents of directories in a tree-like format. 显示目录的层级结构: tree 命令英文理解为树的意思,其功能是创建文件列表,将目录所有文件以树状的形式列出来.linux中的tree命令默认并不会安装,所以需要通过yum install tree -y来安装此命令. [SYNOPSIS] tree [options] [directory] [OPTIONS] -L level:指定要显示的层级: -d:仅列出目

[LeetCode] Find Mode in Binary Search Tree 找二分搜索数的众数

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than or equal to the nod

226反转二叉树 Invert Binary Tree

Invert a binary tree. 4 / 2 7 / \ / 1 3 6 9 to 4 / 7 2 / \ / 9 6 3 1 Trivia:This problem was inspired by this original tweet by Max Howell: Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a wh