UVa 524 - Prime Ring Problem

來源:互聯網
上載者:User

標籤:blog   資料   os   2014   for   io   

題目:把1-n,連續的放到一個環裡,使相鄰的數字和為素數,輸出所有結果。

分析:搜尋+剪枝。如果裸搜,用dancing-links那種拆裝的鏈表,應該差不多滿足16的資料量。

            這裡利用一個性質進行剪枝:相鄰的數字一定是奇偶性不同的數字。

            (如果上述假設不成立,則存在相鄰的奇數或偶數,那麼他們的和一定是大於2的偶數,不是素數)

            根據上面的假設,還有一條推論:只有n為偶數時才有解。

            (n為奇數,一直至少有一對奇數相鄰,同上,矛盾(鴿巢原理))

            因此,每次搜尋的資料其實是n/2,時間複雜度為O((n/2)!* 2^(n/2));

            打表計算,查詢輸出即可。

說明:注意題目沒說,每組輸出間有一個空行。

#include <iostream>#include <cstdlib>#include <cstring>#include <cstdio>using namespace std;int prime[32];int visit[18];int queue[18];int size[18];int ans[18][100000][18];void dfs( int d, int n ){if ( d == n && !prime[queue[d-1]+1] ) {for ( int i = 1 ; i < n ; ++ i )ans[n][size[n]][i] = queue[i];size[n] ++;return;}for ( int i = d%2+1; i <= n ; i += 2 )if ( !visit[i] && !prime[i+queue[d-1]] ) {visit[i] = 1;queue[d] = i;dfs( d+1, n );visit[i] = 0;}}int main(){memset( prime, 0, sizeof(prime) );prime[0] = prime[1] = 1;for ( int i = 2 ; i < 32 ; ++ i ) if ( !prime[i] )for ( int j = 2*i ; j < 32 ; j += i )prime[j] = 1;memset( visit, 0, sizeof(visit) );visit[1] = 1;queue[0] = 1;memset( size, 0, sizeof(size) );for ( int i = 2 ; i <= 16 ; i += 2 )dfs( 1, i );int n,m,t = 0;while ( ~scanf("%d",&n) ) {if ( t ++ ) printf("\n");printf("Case %d:\n",t);m = size[n];for ( int i = 0 ; i < m ; ++ i ) {printf("1");for ( int j = 1 ; j < n ; ++ j )printf(" %d",ans[n][i][j]);printf("\n");}}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.