A -N皇后问题
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Description
Input
Output
Sample Input
Sample Output
Hint
Description
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1 8 5 0
Sample Output
1 92 10
题目分析:这是一道经典的可利用回溯思想解决的问题,即产生冲突返回上一层,题目现在看来不难,当时写了好久
#include<iostream>
using namespace std;
int sum;
int q[12];
int me[12];
void trial(int p,int n){
if(p>=n){
sum=sum+1;
return ;
}
int pre=p;
int flag;
for(int i=0;i<n;i++){
flag=1;
q[pre]=i;
for(int j=0;j<pre;j++){
if(q[j]==q[pre]||pre-i==j-q[j]||pre+i==j+q[j]){
flag=0;
break;
}
}
if(flag==1&&pre<n-1){
trial(pre+1,n);
}
else if(flag==1&&pre==n-1){
sum=sum+1;
}
}
}
int main(){
int n=0;
while(n++<10){
sum=0;
for(int i=0;i<n;i++){
q[0]=i;
trial(1,n);
}
me[n]=sum;
}
while(true){
cin>>n;
sum=0;
if(n==0)
break;
cout<<me[n]<<endl;
}
return 0;
}
B -
Prime Ring Problem
Crawling in process...
Crawling failed
Description
Input
Output
Sample Input
Sample Output
Hint
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.
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.
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
题目分析:本题也是一道运用回溯思想解决的问题,比较基础,适合初学者练习
#include<iostream>
using namespace std;
#define N 22
int num[N];
bool is_pri(int a,int b){
int sum=a+b;
for(int i=2;i*i<=sum;i++){
if(sum==2)
return true;
else if(sum%i==0)
return false;
}
return true;
}
void fback(int l,int n){
if(n==l){
for(int i=0;i<n;i++){
cout<<num[i];
if(i<n-1)
cout<<" ";
else
cout<<endl;
}
}
int flag;
for(int i=2;i<=n;i++){
num[l]=i;
flag=1;
for(int j=0;j<l;j++){
if(i==num[j]){
flag=0;
break;
}
}
if(flag==0){
continue;
}
if(is_pri(i,num[l-1])&&(l<n-1)||is_pri(i,num[0])&&is_pri(i,num[l-1])&&(l==n-1)){
flag=1;
}
else
flag=0;
if(flag==1){
l++;
fback(l,n);
l--;
}
}
}
int main(){
int n,i,l;
i=1;
while(cin>>n){
cout<<"Case "<<i++<<":"<<endl;
l=1;
num[0]=1;
fback(l,n);
cout<<endl;
}
return 0;
}
坚持原创!