HDU 6223 -Infinite Fraction Path(BFS+剪枝)

【题目链接】http://acm.hdu.edu.cn/showproblem.php?pid=6223
在这里插入图片描述
【题意】
给一个长度为 n n 的只包含 [ 0 , 9 ] [0,9] 数字的串,位置从 0 0 开始,下标 i i 的下一个位置是 ( i 2 + 1 )   m o d   n (i^2+1) \ mod \ n ,问其中字符个数为 n n 的路径的最大数字为多少。

【思路】
首先存入最大的数字为开始bfs,寻找所有可能情况,如果当前数字小的数字则停止搜索,或者走到了当前层访问过的位置

#include<set>
#include<map>
#include<cmath>
#include<stack>
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define max(a,b)(a>b?a:b)
using namespace std;
const int maxn=150050;

int n;
char s[maxn];
int a[maxn];
int c[maxn];
bool done[maxn];
vector<int> v;

struct node{
    int p,d;
    node(int pp=0,int dd=0):p(pp),d(dd){}
    bool operator<(const node& e)const{
        if(d==e.d) return a[p]<a[e.p];
        return d>e.d;
    }
};

void bfs(){
    priority_queue<node> que;
    while(que.size()) que.pop();
    int maxv=-1;
    for(int i=0;i<n;++i){
        maxv=max(maxv,a[i]);
        c[i]=0;
        done[i]=false;
    }
    for(int i=0;i<n;++i){
        if(a[i]==maxv) 
			que.push(node(i,0));
    }
    int dep=0;
    v.clear();
    while(!que.empty()){
    	node x=que.top();
    	que.pop();
    	int p=x.p;
    	int d=x.d;
    	if(d>dep){
    		for(int i=0;i<(int)v.size();++i){
    			done[v[i]]=false;
			}
			v.clear();
			dep=d;
		}
		if(d==n) continue;
		if(a[p]<c[d]) continue;
		if(done[p]) continue;
		done[p]=true;
		v.push_back(p);
		c[d]=a[p];
		int nxt=(1LL*p*p+1LL)%n;
		que.push(node(nxt,d+1));
	}
    for(int i=0;i<n;++i){
        printf("%d",c[i]);
    }
    puts("");
}

int main(){
	//freopen("in.txt","r",stdin);
	//freopen("out1.txt","w",stdout);
    int T;
    scanf("%d",&T);
    for(int kase=1;kase<=T;++kase){
        scanf("%d%s",&n,s);
        for(int i=0;i<n;++i) a[i]=s[i]-'0';
        printf("Case #%d: ",kase);
        bfs();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiao_k666/article/details/84035966