zoukankan      html  css  js  c++  java
  • hdu1016Prime Ring Problem 素数环

    Prime Ring Problem

    Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)


    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
     


    自己独立写的第一个dfs,很好很好。

    之后发现小白上有原题。。。。压力很大。。

    AC代码:


    #include<iostream>
    #include<cstring>
    #define MAX 30
    using namespace std;
    
    int ring[MAX], vis[MAX], num, cnt = 1;
    const int pri[11] = {3,5,7,11,13,17,19,23,29,31,37};
    
    void dfs(int cur)
    {
    	if (cur == num - 1)
    	{
    //		cout << cur << ' ' << ring[num - 1] + 1 << endl;
    		int ok = 0;
    		for (int i = 0; i < 11; i++)
    			if (ring[num -1] + 1 == pri[i])
    				ok = 1;
    		if (ok == 0)
    			return;
    		for (int i = 0; i < num - 1; i++)
    			cout << ring[i] << ' ';
    		cout << ring[num - 1] << endl;
    		return;
    	}
    	vis[ring[cur]] = 1;
    	for (int i = 0; i < 11; i++)
    	{
    		if (vis[pri[i] - ring[cur]] == 0 && pri[i] - ring[cur] > 1)
    		{
    		 	if (pri[i] - ring[cur] > num)
    				break;
    			ring[cur + 1] = pri[i] - ring[cur];
    			dfs(cur + 1);
    		}
    	}
    	vis[ring[cur]] = 0;
    }
    
    int main()
    {
    	while(cin >> num)
    	{
    		memset(ring, 0, sizeof (ring));
    		memset(vis, 0, sizeof (vis));
    		ring[0] = 1;
    		cout << "Case " << cnt << ':' << endl;
    		cnt++;
    		dfs(0);
    		cout << endl;
    	}
    }



  • 相关阅读:
    还有更简单的不重复随机数生成方法吗?
    SqlServer数据插入性能小记
    html页面滚动时元素错位解决方案
    为Web页中的Table对象创建一个映射表
    js实现的快速排序
    webkit内核的浏览器为什么removeAttribute('style')会失效?
    setAttribute第三个参数
    Windows转到linux中,文件乱码,文件编码转换
    查看端口的占用
    sndfile
  • 原文地址:https://www.cnblogs.com/java20130723/p/3212170.html
Copyright © 2011-2022 走看看