one recursive approach to solve hdu 1016, list all permutations, solve N-Queens puzzle.

reference: the video of stanford cs106b lecture 10 by Julie Zelenski https://www.youtube.com/watch?v=NdF1QDTRkck

//hdu 1016

#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>

const int MAXN=20;

bool isPrime(int k) {
    static std::string prime={3,5,7,11,13,17,19,23,29,31,37};
    return prime.find(k)!=std::string::npos;
}

void printResult(std::string str) {
    static char strbuf[2*MAXN+5], *p;
    p=strbuf;
    for(auto v:str) { p+=sprintf(p,"%d ",(int)v); }
    *--p=0;
    puts(strbuf);
}

void recSolvePrimeRing(std::string soFar, std::string rest) {
    if(rest.size()==1) {
        if(isPrime(rest[0]+soFar.back()) && isPrime(rest[0]+soFar.front()))
        printResult(soFar+rest);
        return;
    }
    for(int i=0;i<rest.size();++i) {
        int x=rest[i]+soFar.back();
        if(isPrime(rest[i]+soFar.back())) {
            recSolvePrimeRing(soFar+rest[i],rest.substr(0,i)+rest.substr(i+1));
        }
    }
}

void solvePrimeRing(int n) {
    static std::string rest{‘\002‘};
    if(rest.back()<=n)
    for(int i=rest.back()+1;i<=n;++i) rest.push_back(i);
    else rest.resize(n-1);
    recSolvePrimeRing("\001",rest);
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    int n,k=0;
    while(scanf("%d",&n)==1) {
        if(n>0 && n<=MAXN && (n&1)==0) {
            printf("Case %d:\n",++k);
            solvePrimeRing(n);
            putchar(‘\n‘);
        }
    }

    return 0;
}

// Permutation, from the video of stanford cs106b lecture 10 by Julie Zelenski

void RecPermute(string soFar, string rest) {
    if(rest=="") {
        cout << soFar << endl;
    }
    else {
        for(int i=rest.length()-1;i>=0;--i) {
            string next=soFar+rest[i];
            string remaining=rest.substr(0,i)+rest.substr(i+1);
            RecPermute(next,remaining);
        }
    }
}
void ListPermutations(string s) {
    RecPermute("",s);
}

// 8-Queens, 可以推广到N-queens, limitation, N<=255,(howevev 255 is an astronomical number for N-Queens)

// http://blog.csdn.net/qeatzy/article/details/46811451 contains my C++ code of leetcode N-Queens/N-Queens II in this approach

void printQueenBoard(string str) {
static char line[10]="........";
putchar(‘[‘);
for(int i=0, tmp;i<8;++i) {
    tmp=str[i]-‘0‘;
    line[tmp]=‘Q‘;
    printf("\"%s\"",line);
    line[tmp]=‘.‘;
    if(i==7) putchar("],\n");
    else puts(",");
}

void RecSolveQueen(string soFar, string rest) {
    if(rest=="") {
        printQueenBoard(soFar);
    }
    else {
        int flag,len;
        for(int i=0;i<rest.length();++i) {
            flag=1;
            len=soFar.length();
            for(int j=0;j<len;++j) {
                if(rest[i]-soFar[j]==len+i-j || rest[i]-soFar[j]==j-i-len) {
                    flag==0; break;
                }
            }
            if(flag) {
                RecSolveQueen(soFar+rest[i],rest.substr(0,i)+rest.substr(i+1));
            }
        }
    }
}

void eightQueen() {
    string s="01234567";
        // or string s{‘\001‘,‘\002‘,...};
    RecSolveQueen("",s);
}

版权声明:本文为博主原创文章,未经博主允许不得转载。// ps. If in any way improment can be achieved, better performance or whatever, it will be well-appreciated to let me know, thanks in advance.

时间: 2024-10-10 22:05:14

one recursive approach to solve hdu 1016, list all permutations, solve N-Queens puzzle.的相关文章

HDU 1016 Prime Ring Problem 题解

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

HDU 1086:You can Solve a Geometry Problem too

You can Solve a Geometry Problem too Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 6997    Accepted Submission(s): 3385 Problem Description Many geometry(几何)problems were designed in the ACM/

HDU 1016 Prime Ring Problem --- 经典DFS

思路:第一个数填1,以后每个数判断该数和前一个数想加是否为素数,是则填,然后标记,近一步递归求解. 然后记得回溯,继续判断下一个和前一个数之和为素数的数. /* HDU 1016 Prime Ring Problem --- 经典DFS */ #include <cstdio> #include <cstring> int n; bool primer[45], visit[25]; //primer打素数表,visit标记是否访问 int a[25]; //数组a存储放置的数 /

【dfs】hdu 1016 Prime Ring Problem

[dfs]hdu 1016 Prime Ring Problem 题目链接 刚开始接触搜索,先来一道基本题目练练手. 注意对树的深度进行dfs dfs过程中注意回退!!! 素数提前打表判断快一些 参考代码 /*Author:Hacker_vision*/ #include<bits/stdc++.h> #define clr(k,v) memset(k,v,sizeof(k)) using namespace std; const int _max=1e3+10;//素数打表 int n,pr

HDU 1016 Prime Ring Problem (素数筛+DFS)

题目链接 题意 : 就是把n个数安排在环上,要求每两个相邻的数之和一定是素数,第一个数一定是1.输出所有可能的排列. 思路 : 先打个素数表.然后循环去搜..... 1 //1016 2 #include <cstdio> 3 #include <cstring> 4 #include <iostream> 5 6 using namespace std ; 7 8 bool vis[21]; 9 int prime[42] ,cs[21]; 10 int n ; 11

hdu 1016 Prime Ring Problem (简单DFS)

Prime Ring Problem Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 25700    Accepted Submission(s): 11453 Problem Description A ring is compose of n circles as shown in diagram. Put natural numb

hdu 1016 Prime Ring Problem (dfs)

一切见注释. #include <cstdio> #include <iostream> #include <cstring> #include <algorithm> using namespace std; bool vis[22]; int n; int ans[22]; int top; bool isprime(int x)//判断素数 { for(int i=2;i<x;i++) if(x%i==0)return false; return

hdu 1016 Prime Ring Problem (素数环)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1016 题目大意:输入一个n,环从一开始到n,相邻两个数相加为素数. 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 int visit[22],q[100],n; 6 int sushu(int n) 7 { 8 int i; 9 for (i=2

HDU 1016 素数环(深搜)

Prime Ring Problem Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 25134 Accepted Submission(s): 11222 Problem Description A ring is compose of n circles as shown in diagram. Put natural number 1,