题意:给一个长度为n的只包含0~9数字的串,位置从0开始,下标i的下一个位置是(i*i+1)%n,问其中字符个数为n的路径的最大数字为多少。
题解:首先存入最大的数字为开始bfs,然后寻找所有可能情况,这里有两个剪枝:1、当前数字小的数字可以不继续进行。2、当前层走过的位置可以不继续进行。
AC代码:
#include<stdio.h>
#include<algorithm>
#include<queue>
#define N 150005
using namespace std;
typedef long long ll;
char a[N],ans[N];
bool temp[N];
ll sta[N],top;
struct node
{
ll index,step;
node(){}
node(ll index,ll step)
{
this->index=index;
this->step=step;
}
};
priority_queue<node>que;
bool operator<(node A,node B)
{
if(A.step==B.step)return a[A.index]<a[B.index];
return A.step>B.step;
}
int main()
{
ll T;
scanf("%lld",&T);
ll cas=1;
while(T--)
{
ll n;
scanf("%lld",&n);
for(ll i=0;i<n;i++)ans[i]=0;
scanf("%s",a);
char ma=0;
for(ll i=0;i<n;i++)
ma=max(ma,a[i]);
for(ll i=0;i<n;i++)
if(ma==a[i])
que.push(node(i,0));
ll last=0;
while(!que.empty())
{
node k=que.top();
que.pop();
if(last!=k.step)
{
last=k.step;
while(top)temp[sta[--top]]=false;
}
if(ans[k.step]>a[k.index]||k.step>=n||temp[k.index])continue;
sta[top++]=k.index;
temp[k.index]=true;
ans[k.step]=a[k.index];
que.push(node((k.index*k.index+1)%n,k.step+1));
}
while(top)temp[sta[--top]]=false;
printf("Case #%lld: ",cas++);
for(ll i=0;i<n;i++)
printf("%c",ans[i]);
printf("\n");
}
}
本文介绍了一道算法题目,给定一个仅包含0到9的数字字符串,通过特定的跳转规则寻找长度为字符串长度的路径上能组成的最大数字。采用BFS搜索算法,并通过两个剪枝操作来优化搜索过程。

239

被折叠的 条评论
为什么被折叠?



