AVL平衡树没写 不想写
1065 A+B and C (64bit)
为什么不用python?
T = int(input())
for i in range(1, T + 1):
print("Case #%d:" % i, end=" ")
a, b, c = input().split()
if int(a) + int(b) > int(c):
print("true", end="")
else:
print("false", end="")
if i != T:
print()
1067 Sort with Swap(0, i)
猜结论题
举个例子[3, 2, 1, 4, 0],很自然会想到先把位置0调整好 变为[0, 2, 1, 3, 4],需要交换3次。
那1和2位置怎么办,似乎形成了闭环,所以需要主动把0作为中介去交换,作为中介的代价是本来一次就交换好的事情,要多交换两次。
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int n; cin >> n;
vector<int> v(n);
for (int i = 0; i < n; i++) cin >> v[i];
int res = 0;
while (v[0] ^ 0) {
swap(v[v[0]], v[0]);
++res;
}
for (int i = 1; i < n; i++) {
int cnt = 2; // 中介费
while (v[i] ^ i) {
swap(v[v[i]], v[i]);
++cnt;
}
if (cnt > 2) res += cnt;
}
cout << res << '\n';
return 0;
}
1068 Find More Coins
01背包变式,但是,不是计数,而是求具体方案
很自然因为要求输出字典序最小的那一个,所以先对硬币排序,接下来就是选与不选的问题了。
因为字典序最小,所以要优先选,其次不选,这里给出记忆化搜索的代码。
O ( M N ) O(MN) O(MN)
#include <bits/stdc++.h>
using namespace std;
static int dp[10010][110];
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int n, m; cin >> n >> m;
vector<int> v(n), temp;
for (int i = 0; i < n; i++) cin >> v[i];
sort(v.begin(), v.end());
vector<vector<int>> res;
function<void(int, int)> dfs = [&](int i, int tot) -> void {
if (tot == m) {
res.emplace_back(temp);
return;
}
if (i == n || dp[i][tot]) return;
// 优先选
if (tot + v[i] <= m) {
temp.push_back(v[i]);
dfs(i + 1, tot + v[i]);
temp.pop_back();
}
// 其次不选
dfs(i + 1, tot);
// 记忆化 这里只是为了避免重复计算 dp[i][tot]的值并无实际意义
dp[i][tot]++;
};
dfs(0, 0);
sort(res.begin(), res.end());
if (res.empty()) {
cout << "No Solution\n";
} else {
const auto& r = res[0];
for (int i = 0; i < r.size(); i++) {
if (i ^ 0) cout << ' ';
cout << r[i];
}
cout << '\n';
}
return 0;
}