数据结构/算法模板

5.快速幂(x^n)

public double quickMul(double x, long n) {
    double res = 1.0;
    while(n>0) {
        if((n&1)==1) res *= x;
        x *= x;
        n >>= 1;
    }
    return res;
}

4.并查集

const int MAX_N = 1e5+5;
int par[MAX_N * 2];
int rank[MAX_N * 2];

void init(int n) {
	for(int i=1; i<=n; i++) {
		par[i] = i;
		rank[i] = 0;
	}
}

int find(int x) {
	if(par[x] == x) {
		return x;
	} else {
		return par[x] = find(par[x]);
	}
}

void unite(int x, int y) {
	x = find(x);
	y = find(y);
	if(x == y) return;
	if(rank[x] < rank[y]) {
		par[x] = y;
	} else {
		par[y] = x;
		if(rank[x] == rank[y]) rank[x]++;
	}
}

bool same(int a, int b) {
	return find(a) == find(b);
}

3.树状数组

详见 树状数组知识

int n;
int a[1005],c[1005]; //对应原数组和树状数组

int lowbit(int x){
    return x&(-x);
}

void updata(int i,int k){    //在i位置加上k
    while(i <= n){
        c[i] += k;
        i += lowbit(i);
    }
}

int getsum(int i){        //求A[1 - i]的和
    int res = 0;
    while(i > 0){
        res += c[i];
        i -= lowbit(i);
    }
    return res;
}

2.背包问题

0-1背包

基础背景: 给定一个V体积的为盒子,你有n个物品,每个物品的体积 和 价值 分别为vi、wi,求在不超过V的条件下,尽可能让盒子中的物品总价值大。每种物品只能选1次或者0次。

#include<bits/stdc++.h>

using namespace std;

const int N = 5050;
int V, n;
int v[N], W[N];

int main()
{
	cin >> V >> n;
	// 读入v[i] 和 c[i]
	int f[V+1];  //dp数组
	memset(f, 0, size(f));
	for(int i=1; i<=n; i++) {
		for(int j=V; j>=v[i]; j--) {
			f[j] = max(f[j], f[j-v[i]]+w[i]);
		}
	}
	cout << f[V] << "\n"; // f[V]最优解 
	return 0;
}

完全背包

基础背景: 前提条件与0-1背包一致,不同的是,完全背包中,每种物品能有无穷个供选。

#include<bits/stdc++.h>

using namespace std;

const int N = 5050;
int V, n;
int v[N], W[N];

int main()
{
	cin >> V >> n;
	// 读入v[i] 和 c[i]
	int f[V+1];  //dp数组
	memset(f, 0, size(f));
	for(int i=1; i<=n; i++) {
		for(int j=v[i]; j<=V; j++) {
			f[j] = max(f[j], f[j-v[i]]+w[i]);
		}
	}
	cout << f[V] << "\n"; // f[V]最优解 
	return 0;
}

多重背包

基础背景:给定一个V体积的为盒子,你有n个物品,每个物品的体积、价值、个数,分别为vi、wi、ci,求在不超过V的条件下,尽可能使盒子中的物品总价值最大。每种物品可以选0-ci次。

待补充

1.Trie字典树

/**
	Trie字典树模板
*/
public class Trie {
	private class Node {
		char c;
		boolean end;
		Map<Character, Node> children;

		public Node(char _c) {
			c = _c;
			children = new HashMap<>();
		}
	}

	Node root;

	public Trie() {
		root = new Node('#');
	}

        // 构建Trie树
	public void insert(String s) {
		Node p = root;
		for(char c : s.toCharArray()) {
			p.children.putIfAbsent(c, new Node(c));
			p = p.children.get(c);
		}
		p.end = true;
	}

        // 查询是否存在匹配串
	public boolean query(String s) {
		Node p = root;
		for(char c : s.toCharArray()) {
			Node son = p.children.get(c);
			if(son==null) return false;
			p = son;
		}
		return p.end;
	}
}
posted @ 2020-08-12 02:01  Krisone  阅读(200)  评论(0编辑  收藏  举报