编辑代码

#include <iostream>
#include <math.h>
#include <string>
using namespace std;

// 暴力匹配字符串
#if 1
int isMath(const string &s, const string &p){
    if(s.empty() || p.empty()) return -1;
    int n = s.size();
    int m = p.size();
    for(int i = 0; i <= n - m; i++){
        int j = 0;
        for(; j < m; j++){
            if(p[j] != s[i + j])
                break;
        }
        if(j == m) return i;
    }
    return -1;
}

int main() {

    string s1 = "dddysdyyyyss";
    string s2 = "dys";
    cout << isMath(s1, s2) << endl;// 2
    cout << isMath(s1, "") << endl;// -1
    cout << isMath(s1, "sdy") << endl;// 4
	return 0;
}
#endif
/////////////////////////////////////////
// 暴力背包
#if 0
class Commodity {

    public:
        string name;
        int value;
        int weight;

        Commodity(string n, int w, int v) {
            name = n;
            value = v;
            weight = w;
        }
};

void getMaxValueForBackpack(int capacity, Commodity commodities[], int commodityCount) {

    int maxValue = -1;
    int maxValuePos = -1;

    for (int i = 0; i < exp2(commodityCount); i++) {

        //cout << i << endl;

        int pos = i;
        int weight = 0;
        int value = 0;
        int curBit = 0;

        while (pos > 0) {
           
            if (pos & 1 == 1) {
                weight += commodities[curBit].weight;
                value += commodities[curBit].value;

                //cout << weight << " " << value << endl;
            }
            pos = pos >> 1;
            ++curBit;
        }

        if (weight <= capacity && maxValue < value) {
            maxValue = value;
            maxValuePos = i;

             //cout << maxValue << " " << maxValuePos << endl;;
        }
    }

    if (maxValuePos > 0) {

        int curBit = 0;
        cout << "I want to put "<<endl;
        while (maxValuePos > 0) {
            if (maxValuePos & 1 == 1) {
                cout << commodities[curBit].name << "(";
                cout << commodities[curBit].weight << ",";
                cout << commodities[curBit].value << ");" <<endl;
            }
            maxValuePos = maxValuePos >> 1;
            ++curBit;
        }
    }
}
int main() {
    Commodity commodities[] = {
        Commodity("吉他", 15, 1500),
        Commodity("笔记本电脑", 20, 2000),
        Commodity("音响", 30, 3000)
    };

    getMaxValueForBackpack(35, commodities, 3);

     Commodity fourcommodities[] = {
        Commodity("吉他", 15, 1500),
        Commodity("笔记本电脑", 20, 2000),
        Commodity("音响", 30, 3000),
        Commodity("苹果手机", 10, 2000)
    };

    getMaxValueForBackpack(40, fourcommodities, 4);

	return 0;
}
#endif