zoukankan      html  css  js  c++  java
  • hdu1016:Prime Ring Problem(dfs)

    http://acm.hdu.edu.cn/showproblem.php?pid=1016

    Problem Description

    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.

    Input

    n (0 < n < 20).

    Output

    The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.
    You are to write a program that completes above process.
    Print a blank line after each case.

    Sample Input

    6
    8

    Sample Output

    Case 1:
    1 4 3 2 5 6
    1 6 5 2 3 4
    
    Case 2:
    1 2 3 8 5 6 7 4
    1 2 5 8 3 4 7 6
    1 4 7 6 5 8 3 2
    1 6 7 4 3 8 5 2

    题意分析:

    把1-n中的数字按照圆环排列,使每两个相邻的数的和都为素数。

    第一个数字必须为1.

    #include <stdio.h>
    #include <string.h>
    #define N 50
    int a[N], book[N], ans[N], n;
    void P()
    {
    	int i, j;
    	a[0] = a[1] = 1;
    	for(i=2; i<N/2; i++)
    		if(!a[i])
    			for(j=2*i; j<N; j+=i)
    				a[j] = 1;
    }
    void dfs(int i)
    {
    	int j;
    	if(i==n+1 && !a[ans[1]+ans[n]])
    	{
    		for(j=1; j<n; j++)
    			printf("%d ", ans[j]);
    		printf("%d
    ", ans[n]);
    		return ;
    	}
    	for(j=2; j<=n; j++)
    	{
    		if(!a[j+ans[i-1]] && !book[j])
    		{
    			book[j] = 1;
    			ans[i] = j;
    			dfs(i+1);
    			book[j] = 0;
    		}
    	}
    }
    int main()
    {
    	int t;
    	t=1;
    	P();
    	while(scanf("%d", &n)!=EOF)
    	{	
    		memset(book, 0, sizeof(book));
    		printf("Case %d:
    ", t++);
    		ans[1] = 1;
    		book[1] = 1;
    		if(n>1)
    			dfs(2);
    		printf("
    ");
    	}
    	return 0;
    }
  • 相关阅读:
    [转]Vetur can't find `tsconfig.json` or `jsconfig.json` in d:VueProjectsmyroute.
    疾病检验的概率的问题
    约束优化方法之拉格朗日乘子法与KKT条件
    GloVe与word2vec
    RNN、LSTM、GRU
    SVM 常见问题
    深度学习常用优化器算法Optimizer详解
    树模型-常见问题点
    leetcode 打家劫舍
    node 图片处理库 sharp
  • 原文地址:https://www.cnblogs.com/zyq1758043090/p/11852731.html
Copyright © 2011-2022 走看看