zoukankan      html  css  js  c++  java
  • 数据结构/算法模板

    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] << "
    "; // 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] << "
    "; // 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;
    	}
    }
    
  • 相关阅读:
    变量的作用域
    内联函数inline
    数组、函数和指针
    关于android:configChanges的属性的简介
    Android 更新UI的两种方法
    android开发两种退出程序方式
    google内购In-App Billing
    谷歌登陆sdk对接
    openssl测试版本小工具
    关于facebook登陆不安装openssl的情况下怎么获得Facebook Key Hash的简单方法
  • 原文地址:https://www.cnblogs.com/Krisone/p/13488368.html
Copyright © 2011-2022 走看看