cogs 66. [HAOI2004模拟] 数列问题

66. [HAOI2004模拟] 数列问题

★☆   输入文件:dfs3.in   输出文件:dfs3.out   简单对比
时间限制:1 s   内存限制:128 MB

问题描述
试编程将 1 至 N ( N ≤ 15 )的自然数序列 1 , 2 , … , N 重新排列,使任意相邻两数之和为素数。例如 N=3 时有两种排列方案 123 、 321 满足要求。

【输入格式】

输入文件:dfs3.in

第一行:一个整数n(1<=n<=15)

【输出格式】

输出文件:dfs3.out

输出若干行,每行为一种排列方案(排列方案按字典序排列, 相邻数字之间用空格分隔) ),最后一行输出排列方案总数。

【输入样例】

输入文件名:dfs3.in

3

输出文件名:dfs3.out

1 2 3
3 2 1
2

思路:搜索,但是不知道为什么挂了。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,tot;
int num[16],vis[16],yes[12];
void judge(){
    yes[2]=1;yes[3]=1;yes[5]=1;
    yes[7]=1;yes[11]=1;yes[13]=1;
    yes[17]=1;yes[19]=1;yes[23]=1;yes[29]=1;
}
void dfs(int pos){
    if(pos==n+1){
        for(int i=1;i<n;i++)
            if(yes[num[i]+num[i+1]]==0)    return;
        tot++;
        for(int i=1;i<=n;i++)    cout<<num[i]<<" ";
        cout<<endl;
    }
    for(int i=1;i<=n;i++)
        if(!vis[i]){
            vis[i]=1;
            num[pos]=i;
            dfs(pos+1);
            vis[i]=0;
        }
}
int main(){
    freopen("dfs3.in","r",stdin);
    freopen("dfs3.out","w",stdout);
    scanf("%d",&n);
    judge();dfs(1);
    cout<<tot;
}

猜你喜欢

转载自www.cnblogs.com/cangT-Tlan/p/9609989.html
今日推荐