一、B-树:
public class BTreeSET <Key extends Comparable<Key>>
{
private Page root = new Page(true);
public BTreeSET(Key sentinel)
{
add(sentinel);
}
public boolean contains(Key key)
{
return contains(root, key);
}
private boolean contains(Page h, Key key)
{
if (h.isExternal()) return h.contains(key);
else return contains(h.next(key), key);
}
public void add(Key key)
{
add(root, key);
if (root.isFull())
{
Page lefthalf = root;
Page righthalf = root.split();
root = new Page(false);
root.add(lefthalf);
root.add(righthalf);
}
}
public void add(Page h, Key key)
{
if (h.isExernal()) {h.add(key); return;}
Page next = h.next(key);
add(next, key);
if(next.isFull())
h.add(next.split());
next.close();
}
}
二、后缀数组初级实现:
public class SuffixArray
{
private final String[] suffixes;
private final int N;
public SuffixArray(String s)
{
N = s.length();
suffixes = new String[N];
for (int i = 0; i < N; i++)
suffixes[i] = s.substring(i);
Quick3way.sort(suffixes);
}
public int length()
{
return N;
}
public String select(int i)
{
return suffixes[i];
}
public int index(int i)
{
return N - suffixes[i].length();
}
private static int lcp(String s, String t)
{
int N = Math.min(s.length(), t.length());
for (int i = 0; i < N; i++)
if (s.charAt(i) != t.charAt(i))
return i;
return N;
}
public int lcp(int i)
{
return lcp(suffixes[i], suffixes[i-1]);
}
public int rank(String key)
{
int lo = 0;
int hi = N - 1;
while (lo <= hi)
{
int mid = lo + (hi - lo) / 2;
int cmp = key.compareTo(suffixes[mid]);
if (cmp < 0) hi = mid - 1;
else if (cmp > 0) lo = mid + 1;
else return mid;
}
return lo;
}
}
三、最短增广路径的Ford-Fulkerson最大流量算法:
public class FordFulkerson
{
private boolean[] marked;
private FlowEdge[] edgeTo;
private double value;
public FordFulkerson(FlowNetwork G, int s, int t)
{
while (hasAugumentingPath(G, s, t))
{
double bottle = Double.POSITIVE_INFINITY;
for (int v = t; v != s; v = edgeTo[v].other(v))
bottle = Math.min(bottle, edgeTo[v].residualCapacityTo(v));
for (int v = t; v != s; v = edgeTo[v].other(v))
edgeTo[v].addResidualFlowTo(v, bottle);
value += bottle;
}
}
public double Value() {return value;}
public boolean intCut(int v) {return marked[v];}
private boolean hasAugumentingPath(FlowNetwork G, int s, int t)
{
marked = new boolean[G.V()];
edgeTo = new FlowEdge[G.V()];
Queue<Integer> q = new Queue<Integer>();
marked[s] = true;
q.enqueue(s);
while (!q.isEmpty())
{
int v = q.dequeue();
for (FlowEdge e : G.adj(v))
{
int w = e.other(v);
if (e.residualCapacityTo(w) > 0 && !marked[w])
{
edgeTo[w] = e;
marked[w] = true;
q.enqueue(w);
}
}
}
return marked[t];
}
}