Link to the question: Ultraviolet A 552
Ideas:
The time limit is 3 s, and the data is small. Use deep search to find all solutions.
Code:
#include <iostream>#include <string.h>using namespace std;const int MAX_N = 20;int n;int A[MAX_N], vis[MAX_N];int is_prime( int n ){ if ( n == 2 ) return true; for ( int i = 2; i * i <= n; ++i ) if ( n % i == 0 ) return false; return true;}void dfs( int cur ){ if ( cur == n && is_prime( A[0] + A[n - 1] ) ) { int i = 0; for ( i = 0; i < n - 1; ++i ) printf( "%d ", A[i] ); printf( "%d", A[i] ); printf( "\n" ); } else { for ( int i = 2; i <= n; ++i ) { if ( !vis[i] && is_prime( i + A[cur - 1] ) ) { A[cur] = i; vis[i] = 1; dfs( cur + 1 ); vis[i] = 0; } } }}int main( ){ int count = 1; while ( scanf( "%d", &n ) != EOF ) { if ( count != 1 ) printf( "\n" ); A[0] = 1; memset( vis, 0, sizeof( vis ) ); printf( "Case %d:\n", count++ ); dfs( 1 ); } return 0;}
UV 552 prime ring Problem