HDOJ1016.Prime Ring Problem

試題請參見: http://acm.hdu.edu.cn/showproblem.php?pid=1016

題目概述

A ring is compose of n circles as shown in diagram. Put natural number 1, 2, …, n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.

Note: the number of first circle should always be 1.

Image

解題思路

回溯. 生成以1作爲第1個元素的全排列.

遇到的問題

TLE. 於是想到了一個剪枝的方法, 如果當前的序列(如 1 3)已經不能構成質數環(因爲1 + 3 = 4不是質數), 則不要繼續搜索.

PE. 輸出結果的時候, 若是序列中的最後一個數字, 不需要在數字之後加空格.

源代碼

#include <iostream>
#include <cmath>

bool isPrime(int x) {
    for ( int i = 2; i <= std::sqrt(x); ++ i ) {
        if ( x % i == 0 ) {
            return false;
        }
    }
    return true;
}

bool isPrimeLine(int* ring, int n) {
    for ( int i = 1; i < n; ++ i ) {
        if ( !isPrime(ring[i] + ring[i - 1]) ) {
            return false;
        }
    }
    return true;
}

bool isPrimeRing(int* ring, int n) {
    for (int i = 0; i < n; ++i) {
        if (!isPrime(ring[(i + n) % n] + ring[(i + n + 1) % n])) {
            return false;
        }
    }
    return true;
}

void getPrimeRing(int* ring, bool* isUsed, int selectedNumbers, int totalNumbers) {
    if ( selectedNumbers == totalNumbers ) {
        if ( isPrimeRing(ring, totalNumbers) ) {
            for ( int i = 0; i < totalNumbers; ++ i ) {
                std::cout << ring[i] << ( i == totalNumbers - 1 ? "\n" : " " );
            }
        }
    }

    for ( int i = 1; i < totalNumbers; ++ i ) {
        if ( !isUsed[i] ) {
            isUsed[i] = true;
            ring[selectedNumbers] = i + 1;

            if ( isPrimeLine(ring, selectedNumbers + 1) ) {
                getPrimeRing(ring, isUsed, selectedNumbers + 1, totalNumbers);
            }
            isUsed[i] = false;
        }
    }
}

int main() {
    const int MAX_SIZE = 20;

    // Put number 1 as the first element
    bool isUsed[MAX_SIZE] = { 1, 0 };
    int ring[MAX_SIZE] = { 1, 0 };
    int n = 0, currentCase = 0;

    while ( std::cin >> n ) {
        std::cout << "Case " << ++ currentCase << ":" << std::endl;
        getPrimeRing(ring, isUsed, 1, n);
        std::cout << std::endl;
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章