一、压缩字符串
链接:压缩字符串(一)_牛客题霸_牛客网
#include<iostream>
using namespace std;
#include<vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param param string字符串
* @return string字符串
*/
string compressString(string param) {
string s;
s = param;
vector<char> a;
vector<int> num;
for (int i = 0; i < s.size(); i++)
{
if ((s[i] <= 'z' && s[i] >= 'a') || (s[i] >= 'A' && s[i] <= 'Z'))
{
if (a.empty() || s[i] != a.back())
{
a.push_back(s[i]);
num.push_back(1);
}
else
num.back()++;
}
}
string s2;
for (int i = 0; i < a.size(); i++)
{
s2.push_back((a[i]));
if (num[i] != 1)
{
int k = num[i];
string s4;
while (k)
{
s4.push_back(k % 10 + '0');
k /= 10;
}
string::reverse_iterator it = s4.rbegin();
while (it != s4.rend())
{
s2.push_back(*it);
it++;
}
}
}
return s2;
}
};
二、chika和蜜柑
先用甜度排序,再酸度排序,取前K个
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#include<map>
struct mcomp
{
bool operator()(pair<long long, long long>& a, pair<long long, long long>& b)
{
if (a.first == b.first)
return a.second > b.second;
else
return false;
}
}mcomp;
int main()
{
int n, k;
cin >> n >> k;
vector<long long> so;
vector<long long> sw;
for (int i = 0; i < n; i++)
{
long long x;
cin >> x;
so.push_back(x);
}
for (int i = 0; i < n; i++)
{
long long x;
cin >> x;
sw.push_back(x);
}
multimap<long long, long long, greater<long long>> m;
for (int i = 0; i < n; i++)
{
m.insert(pair<long long, long long>(sw[i], so[i]));
}
vector < pair < long long, long long >> v(m.begin(), m.end());
sort(v.begin(), v.begin() + k, mcomp);
long long max1 = 0;
long long max2 = 0;
for (int i = 0; i < k; i++)
{
max1 += v[i].first;
max2 += v[i].second;
}
cout << max2 << ' ' << max1;
}
三、01背包问题
链接:01背包_牛客题霸_牛客网
老问题了,直接复制粘贴
class Solution
{
int dp[1010] = { 0 };
public:
int knapsack(int V, int n, vector<vector<int> >& vw)
{
for(int i = 0; i < n; i++)
{
for(int j = V; j >= vw[i][0]; j--)
{
dp[j] = max(dp[j], dp[j - vw[i][0]] + vw[i][1]);
}
}
return dp[V];
}
};