第四周训练赛
wbw_121124 · · 算法·理论
第四周训练赛总结
| 题目 | 分数 | 改题用时 |
|---|---|---|
| -a-b-c- | 50(TLE) | |
| 数字变换 | 35(WA+TLE) | |
| 红黑树 | 100(AC) | |
| 子集位运算 | 0(WA,有模糊思路) |
-a-b-c-
今天终于又轮到晓莱出题目了。
题目规则非常的简单,直接给定一个只由
A ,B ,C 构成的字符串S 。晓莱希望在
S 字符串上执行以下操作:选择一个连续的
S 的子字符串,如果该字符串是ABC将其替换为BCA。请你输出最多可以执行多少次操作。
暴力
暴力修改查找,
#include<bits/stdc++.h>
typedef int int32;
#define int long long
using namespace std;
int n, cnt;
string s;
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> s;
n = s.size();
s = '#' + s;
for (int i = 1; i <= n - 2; i++)
if (s[i] == 'A' && s[i+1] == 'B' && s[i+2] == 'C')
{
cnt++;
s[i] = 'B';
s[i + 1] = 'C';
s[i + 2] = 'A';
i -= 2;
if(i < 0)
i++;
}
cout << cnt;
return 0;
}
正解
我们发现可以统计 A 的个数,遇到 BC 时
#include<bits/stdc++.h>
typedef int int32;
#define int long long
using namespace std;
int n, cnt, ans;
string s;
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> s;
n = s.size();
s = '#' + s + '#';
for(int i = 1; i <= n; i++)
if (s[i] == 'A')
cnt++;
else if (s[i] == 'B' && s[i + 1] == 'C')
ans += cnt, i++;
else
cnt = 0;
cout << ans;
return 0;
}
数字变换
晓莱现在手上有一个数字
0 ,他希望你能通过一定的数字进行兑换得到数字N 。其中你可以通过以下操作更改数字,但是需要支付一定数量的硬币:
- 将当前数乘
2 ,需要A 个硬币。- 将当前数乘
3 ,需要B 个硬币。- 将当前数乘
5 ,需要C 个硬币。- 将当前数加
1 或减1 ,需要D 个硬币。你可以按任意顺序和任意次数执行这些操作。
最少需要多少硬币才能得到
N ?为了增大题目的难度,设置了
T 组测试用例。
暴力
dfs,应得
#include<bits/stdc++.h>
typedef int int32;
#define int long long
using namespace std;
int t,n,a,b,c,d;
int dfs(int x,int sum)
{
if(sum>=log2(n))
return LLONG_MAX/4;
if(x==0)
return 0;
int mini=LLONG_MAX;
if(!(x%2))
mini=min(mini,dfs(x/2,sum)+a);
if(!(x%3))
mini=min(mini,dfs(x/3,sum)+b);
if(!(x%5))
mini=min(mini,dfs(x/5,sum)+c);
return min({mini,dfs(x-1,sum+1)+d,dfs(x+1,sum+1)+d});
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin>>t;
while(t--)
{
cin>>n>>a>>b>>c>>d;
cout<<dfs(n,0)<<'\n';
}
return 0;
}
正解
记忆化搜索,分类讨论具体见代码。
#include<bits/stdc++.h>
typedef int int32;
#define int unsigned long long
using namespace std;
int t,n,a,b,c,d;
map<int,int>dp;
int dfs(int x)
{
if(x==0)
return 0;
if(dp[x])
return dp[x];
dp[x]=x*d;
if(x%2)
dp[x]=min({dp[x],dfs(x/2)+x%2*d+a,dfs((x+2-x%2)/2)+(2-x%2)*d+a});
else
dp[x]=min(dp[x],dfs(x/2)+a);
if(x%3)
dp[x]=min({dp[x],dfs(x/3)+x%3*d+b,dfs((x+3-x%3)/3)+(3-x%3)*d+b});
else
dp[x]=min(dp[x],dfs(x/3)+b);
if(x%5)
dp[x]=min({dp[x],dfs(x/5)+x%5*d+c,dfs((x+5-x%5)/5)+(5-x%5)*d+c});
else
dp[x]=min(dp[x],dfs(x/5)+c);
return dp[x];
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin>>t;
while(t--)
{
cin>>n>>a>>b>>c>>d;
dp.clear();
cout<<dfs(n)<<'\n';
}
return 0;
}
红黑树
红黑树这里并非是你想象的红黑树。
晓莱在这里拿到了一棵只有红色和黑色两种节点颜色的树。
所谓树,即没有自环、重边和回路的无向连通图。
这棵树有
n 个顶点,n−1 条边。每个顶点被染成了红色或者黑色。晓莱想知道,取两个不同的点作为树上简单路径的起点和终点,它们的简单路径上有且仅有一个黑色点的取法有多少种?
补充描述:
- 树上两点之间的简单路径指连接两点的最短路。
暴力
所有子集位运算
and 之和为\sum_{\\T\in S}f_T 。