Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

提交G++CE,C++就AC,附代码

Posted by 1404010616 at 2015-07-22 10:42:35
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
const int N = 10001;

int prime[N],visit[N],cost[N];

void init()
{
    memset(prime, 0, sizeof(prime));
    for(int i = 2; i*i <= N; ++i)
    {
        if(!prime[i])
            for(int j = i*i; j <= N; j += i)
                prime[j] = 1;
    }
}

int bfs(int a, int b)
{
    queue<int>q;
    q.push(a);
    memset(visit, 1, sizeof(visit));
    memset(cost, 0, sizeof(cost));
    visit[a] = 0;
    cost[a] = 0;
    while(!q.empty())
    {
        int in,out = q.front();
        q.pop();
        for(int i = 1; i < 5; ++i)
        {
            if(i==1)
                for(int j = 1; j < 10; ++j)
                {
                    in = j*1000+out%1000;
                    if(visit[in]&&!prime[in])
                    {
                        if(in==b)return cost[out]+1;
                        visit[in] = 0;
                        q.push(in);
                        cost[in] = cost[out]+1;
                    }
                }
            else
            {
                int site1 = 1,site2 = 1;
                for(int k = 4; k > i; --k)
                    site1 *= 10;
                for(int k = 5-i; k > 0; --k)
                    site2 *= 10;
                for(int j = 0; j < 10; ++j)
                {
                    in = j*site1+out%site1+out/site2*site2;
                    if(visit[in]&&!prime[in])
                    {
                        if(in==b)return cost[out]+1;
                        visit[in] = 0;
                        q.push(in);
                        cost[in] = cost[out]+1;
                    }
                }
            }
        }
    }
    return -1;
}

int main()
{
    int t,a,b;
    init();
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d%d", &a,&b);
        if(a==b)
        {
            printf("0\n");
            continue;
        }
        int ans = bfs(a, b);
        if(ans==-1)printf("Impossible\n");
        else printf("%d\n", ans);
    }
    return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator