您的位置:首页 > 其它

题解-A ring is compose of n circles as shown in diagram.

2018-03-25 21:35 387 查看
[align=left]Problem Description[/align]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.<br><br>Note: the number of first circle should always be 1.<br><br><img src=../../data/images/1016-1.gif><br> 
[align=left]Input[/align]n (0 < n < 20).<br> 
[align=left]Output[/align]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.<br><br>You are to write a program that completes above process.<br><br>Print a blank line after each case.<br> 
[align=left]Sample Input[/align]
68 
[align=left]Sample Output[/align]
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
题目大意:
给你一个数n,输出所有的相邻两数之和为素数(首尾亦满足该条件)的1-n的排列,只输出以1开头的排列
解题思路:
刚看见题时闪过一丝偷懒的惊喜,前几天发现的那个函数next_permutation,正好全排列,我只需要判断一下是条件是否成立就行了,然而并不是所有的STL都是高效的,,试了好几次,默默加了个计数器,当输入为15时,基本上就不行了,,果然,函数的时间复杂度是n!,,数字一大,,准保准的超时,,老老实实写深搜,及时回溯,然后就过了
AC代码(with一段不舍得扔掉的大bug)#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int num[100100],vis[100100];
int n;
int prim(int x)//x是否为素数
{
for(int i=2;i*i<=x;i++)
if(x%i==0)
return 0;
return 1;
}
void dfs(int c)//从1开始搜索
{
if(c==n&&prim(num[n-1]+1))//如果排到了最后一位且与第一位的和满足条件
{
printf("1");//保证第一位是1;
for(int i=1;i<n;i++)//实际从num[]的第二位输出
printf(" %d",num[i]);//一直到n-1位
printf("\n");
}
if(c==n) return ;
for(int i=2;i<=n;i++)
{
if(!vis[i]&&prim(num[c-1]+i))//满足与上一位和为素数,且数字没有被使用过
{
num[c]=i;//放入这个满足条件的数
vis[i]=1;//标记
dfs(c+1);//搜索下一位
vis[i]=0;
}
}
}
int main()
{
int k=1;
while(scanf("%d",&n)!=EOF)
{
memset(vis,0,sizeof(vis));//每一次的n,都要讲标记数组清零
num[0]=1;
vis[1]=1;//标记1被使用
printf("Case %d:\n",k++);
dfs(1);
printf("\n");
}
return 0;
}

//big bug..如下
//#include<iostream>
//#include<stdio.h>
//#include<algorithm>
//#include<math.h>
//using namespace std;
//int mark[25],a[25],n;
//int t=0;
//int su(int a[])
//{
// a[n+1]=a[1];
// for(int j=1;j<=n;j++)
// {
// int x=a[j]+a[j+1];
// for(int i=2;i<=sqrt(x);i++)
// {
// if(x%i==0)
// return -1;
// }
// }
// return 1;
//}
//void soso(int n)
//{
// do
// {
// t++;
// if(a[1]>1){break;return ;}
// if(su(a)>0&&(a[1]==1))
// {
// for(int j=1;j<=n;j++)
// cout<<a[j]<<" ";
// cout<<endl;
// }
// } while(next_permutation(a+1,a+n+1));//&&(a[1]==1)); // 1- 传入地址 2- 参数3是指参与排列的长度
// return ; //如果存在a之后的排列,就返回true;如果a是最后一个排列没
4000
有后记,返回false;每执行一次,a就变成它的后继
//}
//int main()
//{
// //int n;
// while(scanf("%d",&n)!=EOF&&(n<20))
// {
// for(int i=1;i<=20;i++)
// {
// a[i]=i;
// }
// //sizeof(mark,0,sizeof(mark));
// soso(n);
// }
// return 0;
//}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  深搜 回溯
相关文章推荐