- brute force
- 描述:给你一数组,问最少去掉几个数,使数组内,最大数 - 最小数 <= k.
#include <bits/stdc++.h>
//#define LOCAL_DEFINE
using namespace std;
int main(void) {
ios::sync_with_stdio(false);cin.tie(0);
#ifdef LOCAL_DEFINE
freopen("input.txt", "rt", stdin);
#endif
int n, d, ans = 0;
cin >> n >> d;
vector<int> v(n);
for(int i = 0; i < n; ++i) cin >> v[i];
sort(v.begin(), v.end());
for(int i = 0; i < n; ++i) {
int t = v[i] + d;
int id = upper_bound((v.begin() + i), v.end(), t) - v.begin();
int dis = id - i ;
ans = max(ans, dis);
}
cout << n - ans << endl;
#ifdef LOCAL_DEFINE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}
B. Our Tanya is Crying Out Loud
- greedy
- 描述(略)
#include <bits/stdc++.h>
//#define LOCAL_DEFINE
using namespace std;
typedef long long ll;
ll n, k, a, b;
ll ans = 0;
int main(void) {
ios::sync_with_stdio(false);cin.tie(0);
#ifdef LOCAL_DEFINE
freopen("input.txt", "rt", stdin);
#endif
cin >> n >> k >> a >> b;
while(n > 1) {
if(n < k || k == 1) {
ans += (n - 1) * a;
n = 1;
}
else {
if(n % k != 0) {
ans += (n % k) * a;
n -= n % k;
}
else {
int t = n - n / k;
if(t * a < b) ans += t * a;
else ans += b;
n /= k;
}
}
}
cout << ans << endl;
#ifdef LOCAL_DEFINE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}
- constructive algorithms
- 描述 给你一个字符串(全小写),让你求出按照字典序的下一个长度为k的字符串,规定新的字符串不能出现之前没有出现的字母
- 分析
<1>.k > n时,很显然,我们只需在原字符串后面加上出现的字典序最小的字符即可。
<2>.否则,我们贪心的从后往前找如果该字符有出现过更大的字符则替换,再把之后都赋为最小的字符。
#include <bits/stdc++.h>
//#define LOCAL_DEFINE
using namespace std;
int n, k;
string s;
int main(void) {
ios::sync_with_stdio(false);cin.tie(0);
#ifdef LOCAL_DEFINE
freopen("input.txt", "rt", stdin);
#endif
cin >> n >> k >> s;
set<char> st(s.begin(), s.end()); // for(auto c : s) st.insert(c);
if(k > n) {
cout << s;
for(int i = 1; i <= (k - n); ++i)
cout << *st.begin();
return 0;
}
s = s.substr(0, k); // s.resize(k);
for(int i = k - 1;;i--) {
if(s[i] < *st.rbegin()) {
s[i] = *st.lower_bound(s[i] + 1);
break;
}
else
s[i] = *st.begin();
}
cout << s << endl;
#ifdef LOCAL_DEFINE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}