第1部分 TreeMap介绍

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest's Introduction to Algorithms.

Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

Note that this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedSortedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

   SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));

The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

All Map.Entry pairs returned by methods in this class and its views represent snapshots of mappings at the time they were produced. They do not support the Entry.setValue method. (Note however that it is possible to change mappings in the associated map using put.) 

之前已经学习过HashMap和LinkedHashMap了,HashMap不保证数据有序,LinkedHashMap保证数据可以保持插入顺序,而如果我们希望Map可以保持key的大小顺序的时候,我们就需要利用TreeMap了。TreeMap的排序是基于对key的排序。

public class Test {
public static void main(String[] args) {
Map<Integer, String> treeMap = new TreeMap<Integer, String>();
treeMap.put(1, "语文");
treeMap.put(3, "英语");
treeMap.put(2, "数学");
treeMap.put(4, "政治");
treeMap.put(5, "历史");
treeMap.put(6, "地理");
treeMap.put(7, "生物");
treeMap.put(8, "化学");
for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
1 : 语文
2 : 数学
3 : 英语
4 : 政治
5 : 历史
6 : 地理
7 : 生物
8 : 化学

结果是有序的

其大致的结构如下所示:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAdMAAAF4CAIAAACAR4TXAAAgAElEQVR4nO2d328bV3r3598YWJCuCNBAHMC+kC6WCQ4kh2gUSi6VNqWUQpuYdAoIkci0ihzbXMhRX8a0utVry0Rq0/bLJDSTtWjvllsn2vxglERpu4q55WZjZasyN7ohDQS64hWv+F488enxzJCipMOZ4fD7wQNhZnhmdObw4WfOnBkOlToAAABzUayuAAAAdB0wLwAAmA3MCwAAZgPzAivx+/25XM7qWgBgNjAvsBKXyxWLxayuBQBmA/OC/ZDL5YLBYKFQ8Hg8wWCQFq6trfn9fo/H4/f70+m0WD6dTns8Hiq8trZWr9fL5bLH41EUxeVyeTye2dlZ8/cCAKuAecF+iMViLpfL5XLNzs6SedPptKIos7OzhUJhdnZWURTemQ0Ggy6XK5FIrK2tBYNBRVHW1taq1SptxO/3x2IxjDmArgLmBfshFospiiLqkizMZ2dnZ10uV71e39ra0pSkTjFfC6MNoAuBecF+oO4qny0UCoqiFAoF/RJNSc26MC/oTmBesB9gXgAOAswL9oPGpzSkQJfOiHQ6TQUSiYTGvMFg0OPx0DTMC7oTmBfsB31PVhy9rVarfLZcLotDwIVCQbStZnQYgC4B5gX7QW9eUirdIkZ/+UvU/+Uv8bvQ6vU63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UL589m9eMizfPMp3PqdediJ8VtZeiAHzAgDagizzklJJuxSFa7c1S/jy+tp33Lzc0dR7bf0/JsJnafvVjzbaoV2YFwDQLhhj9c//dPAoXP2VoiiFq78SF3qOHPUcOWpYnl7K/Z9lV09vcHisnM3HgjOunl5NsXI2v7Z0Mxac0YffM+Tq6TV8Scoe1T//E8wLAGgLcs2bPvOWuNDV09vcvORWWqI3b+Hqr1w9vTAvAMBpMMbq+W+lhOtQr+tQb/rMW+WV/Na7vw0+61cUJfePl+v5b3P/eNl1qJemKTxPHPU8cVRcPRacdh3qFZekz7zlOtRbXskb/rtYcFqzBekB8wIA2oJE8269+1u/Z5D8qygKWZheSsycURQlFpzek3lnX/i5ZgnMCwBwAoyx+md/lBjllc8Kb7+/9U5Os1yz5CfzCkvW/vmGoii0nEJRlOCzfs12Cm+/T6HfgvSAeQEAbYExVv/0j+aH/2eD/p8NahbmFi7FTr7KIzF9Rr+i54mj1K12HerNLVxqayVhXgBAW7DKvB0RMC8AoC0wxuqf/BFhGDAvAKAtMMbqnxQRhgHzAgDaAmOs/nERYRgwLwCgLTDG6h//F8IwYF4AQFtgjNV/918Iw4B5AQBtgTFW/90fEIYB8wIA2gLMC/MCAMyGMVZf/QPCMGBeAEBbYIzVVwsIw4B5AQBtgTFW/6iAMAyYFwDQFhhj9Q8LCMOAeQEAbYExVv/wPsIwYF4AQFtgjNXv3UcYBswLAGgLMC/MCwAwG8ZY/d++QRgGzAsAaAswL8wLADAbxlj9txsIw4B5AQBtgTFWz20gDAPmBQC0BZ/Px0ADhoeHYV4AQBspg6bwhoJ5AQDSsNpsdoc3FMwLAJDGw4cPrZabfXn48CFvKJgXAADMBuYFAACzgXkBAMBsYF4AADAbmBcAAMzm/wNsUj7tOJQw5wAAAABJRU5ErkJggg==" alt="" />

put的顺序不同,构建的树的结构也是不同的!

使用红黑树的好处是能够使得树具有不错的平衡性,这样操作的速度就可以达到log(n)的水平了。

TreeMap的构造函数

// 默认构造函数。使用该构造函数,TreeMap中的元素按照key的自然排序进行排列。
TreeMap() // 创建的TreeMap包含Map
TreeMap(Map<? extends K, ? extends V> copyFrom) // 指定Tree的比较器
TreeMap(Comparator<? super K> comparator) // 创建的TreeSet包含copyFrom
TreeMap(SortedMap<K, ? extends V> copyFrom)

第2部分 TreeMap数据结构

TreeMap的继承关系

java.lang.Object
↳ java.util.AbstractMap<K, V>
↳ java.util.TreeMap<K, V> public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable {}

TreeMap与Map关系如下图:

从图中可以看出:
(01) TreeMap实现继承于AbstractMap,并且实现了NavigableMap接口。
(02) TreeMap的本质是R-B Tree(红黑树),它包含几个重要的成员变量: root, size, comparator。
  root

是红黑数的根节点。它是Entry类型,Entry是红黑数的节点,它包含了红黑数的6个基本组成成分:key(键)、value(值)、left(左孩
子)、right(右孩子)、parent(父节点)、color(颜色)。Entry节点根据key进行排序,Entry节点包含的内容为value。

  红黑数排序时,根据Entry中的key进行排序;Entry中的key比较大小是根据比较器comparator来进行判断的。
  size是红黑数中节点的个数。

第3部分 TreeMap API源码解析

第3.1部分 TreeMap的红黑树相关内容
TreeMap中于红黑树相关的主要函数有:
1 数据结构
1.1 红黑树的节点颜色--红色

private static final boolean RED = false;

1.2 红黑树的节点颜色--黑色

private static final boolean BLACK = true;

1.3 “红黑树的节点”对应的类。

static final class Entry<K,V> implements Map.Entry<K,V> {
K key;
V value;
Entry<K,V> left;
Entry<K,V> right;
Entry<K,V> parent;
boolean color = BLACK; /**
* Make a new cell with given key, value, and parent, and with
* {@code null} child links, and BLACK color.
*/
Entry(K key, V value, Entry<K,V> parent) {
this.key = key;
this.value = value;
this.parent = parent;
} /**
* Returns the key.
*
* @return the key
*/
public K getKey() {
return key;
} /**
* Returns the value associated with the key.
*
* @return the value associated with the key
*/
public V getValue() {
return value;
} /**
* Replaces the value currently associated with the key with the given
* value.
*
* @return the value associated with the key before this method was
* called
*/
public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
} public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o; return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
} public int hashCode() {
int keyHash = (key==null ? 0 : key.hashCode());
int valueHash = (value==null ? 0 : value.hashCode());
return keyHash ^ valueHash;
} public String toString() {
return key + "=" + value;
}
}

Entry包含了6个部分内容:key(键)、value(值)、left(左孩子)、right(右孩子)、parent(父节点)、color(颜色)
Entry节点根据key进行排序,Entry节点包含的内容为value。

2 相关操作
2.1 左旋

private void rotateLeft(Entry<K,V> p) { ... }

2.2 右旋

private void rotateRight(Entry<K,V> p) { ... }

2.3 插入操作

public V put(K key, V value) { ... }

2.4 插入修正操作
红黑树执行插入操作之后,要执行“插入修正操作”。
目的是:保红黑树在进行插入节点之后,仍然是一颗红黑树

private void fixAfterInsertion(Entry<K,V> x) { ... }

2.5 删除操作

private void deleteEntry(Entry<K,V> p) { ... }

2.6 删除修正操作
红黑树执行删除之后,要执行“删除修正操作”。
目的是保证:红黑树删除节点之后,仍然是一颗红黑树

private void fixAfterDeletion(Entry<K,V> x) { ... }

第3.2部分 TreeMap的构造函数
1 默认构造函数
使用默认构造函数构造TreeMap时,使用java的默认的比较器比较Key的大小,从而对TreeMap进行排序。

/**
* Constructs a new, empty tree map, using the natural ordering of its
* keys. All keys inserted into the map must implement the {@link
* Comparable} interface. Furthermore, all such keys must be
* <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
* a {@code ClassCastException} for any keys {@code k1} and
* {@code k2} in the map. If the user attempts to put a key into the
* map that violates this constraint (for example, the user attempts to
* put a string key into a map whose keys are integers), the
* {@code put(Object key, Object value)} call will throw a
* {@code ClassCastException}.
*/
public TreeMap() {
comparator = null;
}

2 带比较器的构造函数

/**
* Constructs a new, empty tree map, ordered according to the given
* comparator. All keys inserted into the map must be <em>mutually
* comparable</em> by the given comparator: {@code comparator.compare(k1,
* k2)} must not throw a {@code ClassCastException} for any keys
* {@code k1} and {@code k2} in the map. If the user attempts to put
* a key into the map that violates this constraint, the {@code put(Object
* key, Object value)} call will throw a
* {@code ClassCastException}.
*
* @param comparator the comparator that will be used to order this map.
* If {@code null}, the {@linkplain Comparable natural
* ordering} of the keys will be used.
*/
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}

3 带Map的构造函数,Map会成为TreeMap的子集

/**
* Constructs a new tree map containing the same mappings as the given
* map, ordered according to the <em>natural ordering</em> of its keys.
* All keys inserted into the new map must implement the {@link
* Comparable} interface. Furthermore, all such keys must be
* <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
* a {@code ClassCastException} for any keys {@code k1} and
* {@code k2} in the map. This method runs in n*log(n) time.
*
* @param m the map whose mappings are to be placed in this map
* @throws ClassCastException if the keys in m are not {@link Comparable},
* or are not mutually comparable
* @throws NullPointerException if the specified map is null
*/
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}

该构造函数会调用putAll()将m中的所有元素添加到TreeMap中。putAll()源码如下:
从中,我们可以看出putAll()就是将m中的key-value逐个的添加到TreeMap中。

public void putAll(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
put(e.getKey(), e.getValue());
}

4 带SortedMap的构造函数,SortedMap会成为TreeMap的子集

public TreeMap(SortedMap<K, ? extends V> m) {
comparator = m.comparator();
try {
buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
}

该构造函数不同于上一个构造函数,在上一个构造函数中传入的参数是Map,Map不是有序的,所以要逐个添加。
而该构造函数的参数是SortedMap是一个有序的Map,我们通过buildFromSorted()来创建对应的Map。
buildFromSorted涉及到的代码如下:

// 根据已经一个排好序的map创建一个TreeMap
// 将map中的元素逐个添加到TreeMap中,并返回map的中间元素作为根节点。
private final Entry<K,V> buildFromSorted(int level, int lo, int hi,
int redLevel,
Iterator it,
java.io.ObjectInputStream str,
V defaultVal)
throws java.io.IOException, ClassNotFoundException { if (hi < lo) return null; // 获取中间元素
int mid = (lo + hi) / 2; Entry<K,V> left = null;
// 若lo小于mid,则递归调用获取(middel的)左孩子。
if (lo < mid)
left = buildFromSorted(level+1, lo, mid - 1, redLevel,
it, str, defaultVal); // 获取middle节点对应的key和value
K key;
V value;
if (it != null) {
if (defaultVal==null) {
Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next();
key = entry.getKey();
value = entry.getValue();
} else {
key = (K)it.next();
value = defaultVal;
}
} else { // use stream
key = (K) str.readObject();
value = (defaultVal != null ? defaultVal : (V) str.readObject());
} // 创建middle节点
Entry<K,V> middle = new Entry<K,V>(key, value, null); // 若当前节点的深度=红色节点的深度,则将节点着色为红色。
if (level == redLevel)
middle.color = RED; // 设置middle为left的父亲,left为middle的左孩子
if (left != null) {
middle.left = left;
left.parent = middle;
} if (mid < hi) {
// 递归调用获取(middel的)右孩子。
Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
it, str, defaultVal);
// 设置middle为left的父亲,left为middle的左孩子
middle.right = right;
right.parent = middle;
} return middle;
}

要理解buildFromSorted,重点说明以下几点:
第一,buildFromSorted是通过递归将SortedMap中的元素逐个关联。
第二,buildFromSorted返回middle节点(中间节点)作为root。
第三,buildFromSorted添加到红黑树中时,只将level == redLevel的节点设为红色。第level级节点,实际上是buildFromSorted转换成红黑树后的最底端(假设根节点在最上方)的节点;只将红黑树最底端的阶段着色为红色,其余都是黑色。

 第3.3部分 TreeMap的put方法

/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
*
* @return the previous value associated with {@code key}, or
* {@code null} if there was no mapping for {@code key}.
* (A {@code null} return can also indicate that the map
* previously associated {@code null} with {@code key}.)
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
*/
// 将"key, value"添加到TreeMap中
// 理解TreeMap的前提是掌握"红黑树"。
// 若理解"红黑树中添加节点"的算法,则很容易理解put。
public V put(K key, V value) {
Entry<K,V> t = root;
// 若红黑树为空,则插入根节点
if (t == null) {
compare(key, key); // type check
root = new Entry<K,V>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
// 在二叉树(红黑树是特殊的二叉树)中,找到(key, value)的插入位置。
// 红黑树是以key来进行排序的,所以这里以key来进行查找。
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
// 新建红黑树的节点(e)
Entry<K,V> e = new Entry<K,V>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
// 红黑树插入节点后,不再是一颗红黑树;
// 这里通过fixAfterInsertion的处理,来恢复红黑树的特性。
fixAfterInsertion(e);
size++;
modCount++;
return null;
}

第3.4部分 TreeMap的get方法

/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code key} compares
* equal to {@code k} according to the map's ordering, then this
* method returns {@code v}; otherwise it returns {@code null}.
* (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <em>necessarily</em>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
*/
// 获取“键(key)”对应的“值(value)”
public V get(Object key) {
// 获取“键”为key的节点(p)
Entry<K,V> p = getEntry(key);
// 若节点(p)为null,返回null;否则,返回节点对应的值
return (p==null ? null : p.value);
}
/**
* Returns this map's entry for the given key, or {@code null} if the map
* does not contain an entry for the key.
*
* @return this map's entry for the given key, or {@code null} if the map
* does not contain an entry for the key
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
*/
// 获取TreeMap中“键”为key的节点
final Entry<K,V> getEntry(Object key) {
// 若“比较器”为null,则通过getEntryUsingComparator()获取“键”为key的节点
if (comparator != null)
return getEntryUsingComparator(key);
if (key == null)
throw new NullPointerException();
Comparable<? super K> k = (Comparable<? super K>) key;
// 将p设为根节点
Entry<K,V> p = root;
while (p != null) {
int cmp = k.compareTo(p.key);
// 若“p的key” < key,则p=“p的左孩子”
if (cmp < 0)
p = p.left;
// 若“p的key” > key,则p=“p的左孩子”
else if (cmp > 0)
p = p.right;
// 若“p的key” = key,则返回节点p
else
return p;
}
return null;
}

参考资料

TreeMap (Java Platform SE 8)
浅谈算法和数据结构: 九 平衡查找树之红黑树
Java提高篇(二七)——-TreeMap
数据结构之红黑树
wikipedia-红黑树
Red-Black Trees
How TreeMap searches successor for given Entry?

TreeMap源代码深入剖析的更多相关文章

  1. 【Java集合源代码剖析】TreeMap源代码剖析

    转载请注明出处:http://blog.csdn.net/ns_code/article/details/36421085 前言 本文不打算延续前几篇的风格(对全部的源代码加入凝视),由于要理解透Tr ...

  2. 转:【Java集合源码剖析】TreeMap源码剖析

    前言 本文不打算延续前几篇的风格(对所有的源码加入注释),因为要理解透TreeMap的所有源码,对博主来说,确实需要耗费大量的时间和经历,目前看来不大可能有这么多时间的投入,故这里意在通过于阅读源码对 ...

  3. Java集合系列之TreeMap源代码分析

    一.概述 TreeMap是基于红黑树实现的.因为TreeMap实现了java.util.sortMap接口,集合中的映射关系是具有一定顺序的,该映射依据其键的自然顺序进行排序或者依据创建映射时提供的C ...

  4. 【源代码】TreeMap源代码剖析

    注:下面源代码基于jdk1.7.0_11 之前介绍了一系列Map集合中的详细实现类,包含HashMap,HashTable,LinkedHashMap.这三个类都是基于哈希表实现的,今天我们介绍还有一 ...

  5. Java集合:TreeMap源码剖析

    一.概念 TreeMap是基于红黑树结构实现的一种Map,要分析TreeMap的实现首先就要对红黑树有所了解. 要了解什么是红黑树,就要了解它的存在主要是为了解决什么问题,对比其他数据结构比如数组,链 ...

  6. java TreeMap 源代码分析 平衡二叉树

    TreeMap 的实现就是红黑树数据结构,也就说是一棵自平衡的排序二叉树,这样就可以保证当需要快速检索指定节点. TreeSet 和 TreeMap 的关系 为了让大家了解 TreeMap 和 Tre ...

  7. [Java] TreeMap - 源代码学习笔记

    TreeMap 实现了 SortedMap 和 NavigableMap 接口,所有本文还会记录 SortedMap 和 NavigableMap 的阅读笔记. SortedMap 1. 排序的比较应 ...

  8. TreeMap - 源代码学习笔记

    TreeMap 实现了 NavigableMap 接口,而NavigableMap 接口继承于 SortedMap接口. 所有本文还会记录 SortedMap 和 NavigableMap 的阅读笔记 ...

  9. TreeMap源码剖析

    原文  http://blog.csdn.net/chdjj/article/details/38782221 主题 源码分析红黑树 注:以下源码基于jdk1.7.0_11 之前介绍了一系列Map集合 ...

随机推荐

  1. 黑马程序员_java基础笔记(07)...IO流

    —————————— ASP.Net+Android+IOS开发..Net培训.期待与您交流!—————————— IO(InputStream,outputStream)字节流 (Reader,Wr ...

  2. Mongoose关于当天日期的查询

    参考:https://blog.csdn.net/difffate/article/details/70312894 Ant Design Pro中,有关于日期的查询条件,但日期是以数字表示的 Req ...

  3. 关于mysql中storage_engine中 MYISAM 和 INNODB 的选择

    简单点说 读操作多用myisam 写操作多用innodb 不过现在大家好像基本都用innodb,本人小白一个就直接用InnoDB. MySQL自20多年前成立以来一直支持可插拔存储引擎,但在一段相当长 ...

  4. softmax 杂谈

    在多分类问题中,我们可以使用 softmax 函数,对输出的值归一化为概率值.下面举个例子: import sys sys.path.append("E:/zlab/") from ...

  5. Python 入门之基本数据类型

    为什么我要学习Python这门语言呢?其实很简单,我想拓展技术面的同时,尝试更多的方向,可能最后会不了了之,谁知道呢?有可能的话,我会向爬虫和数据分析这个方向走.所以也就开始了我的Python学习之旅 ...

  6. 见微知著(一):解析ctf中的pwn--Fast bin里的UAF

    在网上关于ctf pwn的入门资料和writeup还是不少的,但是一些过渡的相关知识就比较少了,大部分赛棍都是在不断刷题中总结和进阶的.所以我觉得可以把学习过程中的遇到的一些问题和技巧总结成文,供大家 ...

  7. hihocoder 1526 序列的值

    题面在这里! 好久没做题啦,养生一下qwq 推一推贡献就会发现这TM就是一个水题啊! #include<bits/stdc++.h> #define ll long long using ...

  8. 【Dijkstra】POJ1062-昂贵的聘礼

    由于物品编号从1开始,我们假定0也是一个物品作为起点,它到其它物品的距离就是各个物品的原始价值.开始时,如果两种物品主人的等级限制M在规定范围以内,且j能用i替换,则将优惠价格视作从i到j的一条权值为 ...

  9. 利用Pastezort渗透win7

    下载Pastezort git clone https://github.com/ZettaHack/PasteZort.git 给Pastezort文件夹提升权限 /root/PasteZort/ ...

  10. [BZOJ4832]抵制克苏恩

    [BZOJ4832]抵制克苏恩 思路: \(f[i][j][k][l]\)表示打了\(i\)次,血量为\(1\sim 3\)的随从有\(j,k,l\)个的期望.转移时注意避免重复. 源代码: #inc ...