K-Tokitsukaze and Password (easy)
原题链接:K-Tokitsukaze and Password (easy)_2024牛客寒假算法基础集训营2 (nowcoder.com)
题目描述
思路:这题给的数据范围很小,所以可以暴力枚举,a,b,c,d,_的值逐一枚举,再逐字符判断,若有其中之一,再将其值与原字符串值进行替换,将最后得到的值先进性有无先导0的判断,再将其化为整数,因为暴力枚举替换字母存在重复的可能,将最后得到的整数先存入集合中,最后再输出set.size()即可。
代码:
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
void slove()
{
set<int> smod;
int n,y;
string s,temp;
cin>>n>>s>>y;
char a,b,c,d,_;
for(a='0';a<='9';a++)
{
for(b='0';b<='9';b++)
{
for(c='0';c<='9';c++)
{
for(d='0';d<='9';d++)
{
for(_='0';_<='9';_++)
{
if(a==b||a==c||a==d||b==c||b==d||c==d)
continue;
temp=s;
for(auto& x : temp)
{
if(x=='a')
x=a;
else if(x=='b')
x=b;
else if(x=='c')
x=c;
else if(x=='d')
x=d;
else if(x=='_')
x=_;
}
if(n>1 && temp[0]=='0')
continue;
int out=stoi(temp);
/*stoi是C++标准库提供的函数,
用于将包含数字字符的字符串转换为整数值。
它接受一个字符串作为输入,并返回一个整数。*/
if(out<=y && out%8==0)
smod.insert(out);
}
}
}
}
}
cout<<smod.size()<<endl;
}
signed main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int t;
cin>>t;
while(t--)
{
slove();
}
return 0;
}
D - Tokitsukaze and Slash Draw
原题链接 :D-Tokitsukaze and Slash Draw_2024牛客寒假算法基础集训营2 (nowcoder.com)
题意:
n张牌,欲使从下往上数第k张通过任意次数使用m种调整方式到达最上面。m种调整方式会将最上面ai张牌花费bi的cost移动到最下面,须支付最小的cost,若可行则输出cost,否则输出-1。
思路:
通过dp,每次调整位置处于从下往上数第(k+ai)%n张,通过bfs,判断下一个位置是否已经走过以及cost的大小,最后算出cost。
代码:
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
int n,m,k,pos;
int v[5005],a[5005],b[5005];
queue <int> q;
void bfs()
{
while(!q.empty())
{
int temp=q.front();//这张牌的位置
q.pop();
for(int i=1;i<=m;i++)
{
pos=(temp+a[i])%n;//调整后的位置
if(v[pos]!=-1 && v[temp]+b[i]>=v[pos])
continue;
v[pos]=v[temp]+b[i];
q.push(pos);
}
}
}
void slove()
{
cin>>n>>m>>k;
pos=0;
while(!q.empty())
{
q.pop();//清空队列,防止干扰
}
memset(v,-1,sizeof(v));
/*"memset(v,-1,sizeof(v));"的意思是将数组
或缓冲区"v"的所有元素设置为值-1。
函数"memset"用于用特定值初始化一块内存,
它接受三个参数:要填充的内存块的地址(v)、
要设置的值(-1)和内存块的大小(sizeof(v))*/
for(int i=1;i<=m;i++)
{
cin>>a[i]>>b[i];
}
v[k-1]=0;
q.push(k-1);
bfs();
cout<<v[n-1]<<endl;
}
signed main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int t;
cin>>t;
while(t--)
{
slove();
}
return 0;
}