const std = @import("std.zig");
const assert = std.debug.assert;
const testing = std.testing;
const Order = std.math.Order;
pub fn Treap(comptime Key: type, comptime compareFn: anytype) type {
    return struct {
        const Self = @This();
        
        
        fn compare(a: Key, b: Key) Order {
            return compareFn(a, b);
        }
        root: ?*Node = null,
        prng: Prng = .{},
        
        
        
        const Prng = struct {
            xorshift: usize = 0,
            fn random(self: *Prng, seed: usize) usize {
                
                if (self.xorshift == 0) {
                    self.xorshift = seed;
                }
                
                const shifts = switch (@bitSizeOf(usize)) {
                    64 => .{ 13, 7, 17 },
                    32 => .{ 13, 17, 5 },
                    16 => .{ 7, 9, 8 },
                    else => @compileError("platform not supported"),
                };
                self.xorshift ^= self.xorshift >> shifts[0];
                self.xorshift ^= self.xorshift << shifts[1];
                self.xorshift ^= self.xorshift >> shifts[2];
                assert(self.xorshift != 0);
                return self.xorshift;
            }
        };
        
        pub const Node = struct {
            key: Key,
            priority: usize,
            parent: ?*Node,
            children: [2]?*Node,
        };
        
        
        pub fn getMin(self: Self) ?*Node {
            var node = self.root;
            while (node) |current| {
                node = current.children[0] orelse break;
            }
            return node;
        }
        
        
        pub fn getMax(self: Self) ?*Node {
            var node = self.root;
            while (node) |current| {
                node = current.children[1] orelse break;
            }
            return node;
        }
        
        
        pub fn getEntryFor(self: *Self, key: Key) Entry {
            var parent: ?*Node = undefined;
            const node = self.find(key, &parent);
            return Entry{
                .key = key,
                .treap = self,
                .node = node,
                .context = .{ .inserted_under = parent },
            };
        }
        
        
        
        pub fn getEntryForExisting(self: *Self, node: *Node) Entry {
            assert(node.priority != 0);
            return Entry{
                .key = node.key,
                .treap = self,
                .node = node,
                .context = .{ .inserted_under = node.parent },
            };
        }
        
        pub const Entry = struct {
            
            key: Key,
            
            treap: *Self,
            
            node: ?*Node,
            
            context: union(enum) {
                
                inserted_under: ?*Node,
                
                removed,
            },
            
            pub fn set(self: *Entry, new_node: ?*Node) void {
                
                defer self.node = new_node;
                if (self.node) |old| {
                    if (new_node) |new| {
                        self.treap.replace(old, new);
                        return;
                    }
                    self.treap.remove(old);
                    self.context = .removed;
                    return;
                }
                if (new_node) |new| {
                    
                    
                    
                    var parent: ?*Node = undefined;
                    switch (self.context) {
                        .inserted_under => |p| parent = p,
                        .removed => assert(self.treap.find(self.key, &parent) == null),
                    }
                    self.treap.insert(self.key, parent, new);
                    self.context = .{ .inserted_under = parent };
                }
            }
        };
        fn find(self: Self, key: Key, parent_ref: *?*Node) ?*Node {
            var node = self.root;
            parent_ref.* = null;
            
            while (node) |current| {
                const order = compare(key, current.key);
                if (order == .eq) break;
                parent_ref.* = current;
                node = current.children[@boolToInt(order == .gt)];
            }
            return node;
        }
        fn insert(self: *Self, key: Key, parent: ?*Node, node: *Node) void {
            
            node.key = key;
            node.priority = self.prng.random(@ptrToInt(node));
            node.parent = parent;
            node.children = [_]?*Node{ null, null };
            
            const link = if (parent) |p| &p.children[@boolToInt(compare(key, p.key) == .gt)] else &self.root;
            assert(link.* == null);
            link.* = node;
            
            while (node.parent) |p| {
                if (p.priority <= node.priority) break;
                const is_right = p.children[1] == node;
                assert(p.children[@boolToInt(is_right)] == node);
                const rotate_right = !is_right;
                self.rotate(p, rotate_right);
            }
        }
        fn replace(self: *Self, old: *Node, new: *Node) void {
            
            new.key = old.key;
            new.priority = old.priority;
            new.parent = old.parent;
            new.children = old.children;
            
            const link = if (old.parent) |p| &p.children[@boolToInt(p.children[1] == old)] else &self.root;
            assert(link.* == old);
            link.* = new;
            
            for (old.children) |child_node| {
                const child = child_node orelse continue;
                assert(child.parent == old);
                child.parent = new;
            }
        }
        fn remove(self: *Self, node: *Node) void {
            
            while (node.children[0] orelse node.children[1]) |_| {
                self.rotate(node, rotate_right: {
                    const right = node.children[1] orelse break :rotate_right true;
                    const left = node.children[0] orelse break :rotate_right false;
                    break :rotate_right (left.priority < right.priority);
                });
            }
            
            const link = if (node.parent) |p| &p.children[@boolToInt(p.children[1] == node)] else &self.root;
            assert(link.* == node);
            link.* = null;
            
            node.key = undefined;
            node.priority = 0;
            node.parent = null;
            node.children = [_]?*Node{ null, null };
        }
        fn rotate(self: *Self, node: *Node, right: bool) void {
            
            
            
            
            
            
            
            const parent = node.parent;
            const target = node.children[@boolToInt(!right)] orelse unreachable;
            const adjacent = target.children[@boolToInt(right)];
            
            target.children[@boolToInt(right)] = node;
            node.children[@boolToInt(!right)] = adjacent;
            
            node.parent = target;
            target.parent = parent;
            if (adjacent) |adj| adj.parent = node;
            
            const link = if (parent) |p| &p.children[@boolToInt(p.children[1] == node)] else &self.root;
            assert(link.* == node);
            link.* = target;
        }
    };
}
fn SliceIterRandomOrder(comptime T: type) type {
    return struct {
        rng: std.rand.Random,
        slice: []T,
        index: usize = undefined,
        offset: usize = undefined,
        co_prime: usize,
        const Self = @This();
        pub fn init(slice: []T, rng: std.rand.Random) Self {
            return Self{
                .rng = rng,
                .slice = slice,
                .co_prime = blk: {
                    if (slice.len == 0) break :blk 0;
                    var prime = slice.len / 2;
                    while (prime < slice.len) : (prime += 1) {
                        var gcd = [_]usize{ prime, slice.len };
                        while (gcd[1] != 0) {
                            const temp = gcd;
                            gcd = [_]usize{ temp[1], temp[0] % temp[1] };
                        }
                        if (gcd[0] == 1) break;
                    }
                    break :blk prime;
                },
            };
        }
        pub fn reset(self: *Self) void {
            self.index = 0;
            self.offset = self.rng.int(usize);
        }
        pub fn next(self: *Self) ?*T {
            if (self.index >= self.slice.len) return null;
            defer self.index += 1;
            return &self.slice[((self.index *% self.co_prime) +% self.offset) % self.slice.len];
        }
    };
}
const TestTreap = Treap(u64, std.math.order);
const TestNode = TestTreap.Node;
test "std.Treap: insert, find, replace, remove" {
    var treap = TestTreap{};
    var nodes: [10]TestNode = undefined;
    var prng = std.rand.DefaultPrng.init(0xdeadbeef);
    var iter = SliceIterRandomOrder(TestNode).init(&nodes, prng.random());
    
    iter.reset();
    while (iter.next()) |node| {
        const key = prng.random().int(u64);
        
        var entry = treap.getEntryFor(key);
        try testing.expectEqual(entry.key, key);
        try testing.expectEqual(entry.node, null);
        
        entry.set(node);
        try testing.expectEqual(node.key, key);
        try testing.expectEqual(entry.key, key);
        try testing.expectEqual(entry.node, node);
    }
    
    iter.reset();
    while (iter.next()) |node| {
        const key = node.key;
        
        var entry = treap.getEntryFor(node.key);
        try testing.expectEqual(entry.key, key);
        try testing.expectEqual(entry.node, node);
        try testing.expectEqual(entry.node, treap.getEntryForExisting(node).node);
    }
    
    iter.reset();
    while (iter.next()) |node| {
        const key = node.key;
        
        var entry = treap.getEntryForExisting(node);
        try testing.expectEqual(entry.key, key);
        try testing.expectEqual(entry.node, node);
        var stub_node: TestNode = undefined;
        
        entry.set(&stub_node);
        try testing.expectEqual(entry.node, &stub_node);
        try testing.expectEqual(entry.node, treap.getEntryFor(key).node);
        try testing.expectEqual(entry.node, treap.getEntryForExisting(&stub_node).node);
        
        entry.set(node);
        try testing.expectEqual(entry.node, node);
        try testing.expectEqual(entry.node, treap.getEntryFor(key).node);
        try testing.expectEqual(entry.node, treap.getEntryForExisting(node).node);
    }
    
    iter.reset();
    while (iter.next()) |node| {
        const key = node.key;
        
        var entry = treap.getEntryForExisting(node);
        try testing.expectEqual(entry.key, key);
        try testing.expectEqual(entry.node, node);
        
        entry.set(null);
        try testing.expectEqual(entry.node, null);
        try testing.expectEqual(entry.node, treap.getEntryFor(key).node);
        
        entry.set(node);
        try testing.expectEqual(entry.node, node);
        try testing.expectEqual(entry.node, treap.getEntryFor(key).node);
        try testing.expectEqual(entry.node, treap.getEntryForExisting(node).node);
        
        entry.set(null);
        try testing.expectEqual(entry.node, null);
        try testing.expectEqual(entry.node, treap.getEntryFor(key).node);
    }
}