首页 > ACM题库 > HDU-杭电 > HDU 3823-Prime Friend-最小生成树-[解题报告]HOJ
2015
04-13

HDU 3823-Prime Friend-最小生成树-[解题报告]HOJ

Prime Friend

问题描述 :

Besides the ordinary Boy Friend and Girl Friend, here we define a more academic kind of friend: Prime Friend. We call a nonnegative integer A is the integer B’s Prime Friend when the sum of A and B is a prime.
So an integer has many prime friends, for example, 1 has infinite prime friends: 1, 2, 4, 6, 10 and so on. This problem is very simple, given two integers A and B, find the minimum common prime friend which will make them not only become primes but also prime neighbor. We say C and D is prime neighbor only when both of them are primes and integer(s) between them is/are not.

输入:

The first line contains a single integer T, indicating the number of test cases.
Each test case only contains two integers A and B.

Technical Specification

1. 1 <= T <= 1000
2. 1 <= A, B <= 150

输出:

The first line contains a single integer T, indicating the number of test cases.
Each test case only contains two integers A and B.

Technical Specification

1. 1 <= T <= 1000
2. 1 <= A, B <= 150

样例输入:

2
2 4
3 6

样例输出:

Case 1: 1
Case 2: -1

素数筛选 特判

题意:给出两个数字a,b。使a+x, b+x都是素数,并且它们之间没有素数。求出这样的最小的x。

分析:由于无论a,b与什么数相加之间的差值都相等,所以实际上求的是大于b的与其前一个数的差值是a-b的素数。所以该题的关键是将20000000之前的素数打表,然后求其每个之间的差值,相等的存放到同一个数组中。

AC代码:

#include<iostream>
#include<vector>
#include<stdio.h>
#include<string.h>
using namespace std;

const int MAXN = 200000010;

int a[MAXN];
bool b[MAXN];
vector <int>sub[155];
int main(){
    memset(b, 0, sizeof(b));
    b[1] = 1;
    for(int i = 2; i*i <= MAXN; i++){
        if(b[i] == 1)
            continue;
        for(int j = i*2; j <= MAXN; j += i){
            b[j] = 1;
        }
    }
    int times = 0;
    for(int i = 2; i <= MAXN; i++){
        if(b[i] == 0){
            a[times] = i;
            times++;
        }
    }
    for(int i = 0; i < times-1; i++){
        int temp = a[i+1] - a[i];
        if(temp>150)
            continue;
        sub[temp].push_back(a[i+1]);
    }
    int m;
    scanf("%d", &m);
    int sum = 0;
    while(m--){
       sum++;
       long long x, y;
       cin >> x >> y;
       int temp1 = abs(x - y);
       int temp2 = x > y ? x : y;
       long long res = 0;
       for(int i = 0;i < sub[temp1].size(); i++){
            if(sub[temp1][i] >= temp2){
                res = sub[temp1][i];
                break;
            }
        }
       printf("Case %d: ", sum);
       if(res == 0)
           puts("-1");
       else
           printf("%lld\n", res - temp2);
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

参考:http://blog.csdn.net/chuck_0430/article/details/16905607


  1. simple, however efficient. A lot of instances it is difficult to get that a??perfect balancea?? among usability and appearance. I must say that youa??ve done a exceptional task with this. Also, the blog masses quite fast for me on Web explore.

  2. 有两个重复的话结果是正确的,但解法不够严谨,后面重复的覆盖掉前面的,由于题目数据限制也比较严,所以能提交通过。已更新算法