HDU1052 素数环问题
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
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define M 40
int isPrime[M];
int res[M>>1];
int vis[M>>1];
int count;
void prime()//求出1-40的所有素数
{
int i, j;
for(i=1; i<M; ++i)
{
int flag = 1;
for(j=2; j*j<=i; ++j)
{
if(i%j == 0)
{
flag = 0;
break;
}
}
if(flag)
isPrime[i]=1;
}
}
void dfs(int cur,int n){
int i;
if(cur==n&&isPrime[res[n-1]+res[0]]){
for(i=0;i<n-1;i++)
printf("%d ",res[i]);
printf("%d\n",res[i]);
}
else{
for(i=2;i<=n;i++){
if(!vis[i]&&isPrime[res[cur-1]+i]){
res[cur]=i;
vis[i]=1;
dfs(cur+1,n);
vis[i] = 0;
}
}
}
}
int main()
{
int n;
prime();
int count=0;
while(scanf("%d",&n)!=EOF){
count++;
printf("Case %d:\n", count);
memset(vis, 0, sizeof(vis));
res[0] = 1;
dfs(1, n);
printf("\n");
}
return 0;
}
TOJ 工作分配
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int work[16][16];
int vis[16];
int sum,minn;
int n;
void dfs(int cur){
if(cur>=n) return;
for(int i=0;i<n;i++){
if(!vis[i]){
vis[i]=0;
sum+=work[cur][i];
if(cur==n-1){
if(sum<minn){
minn=sum;
}
}
else if(sum<minn) dfs(cur+1);
vis[i]=0;
sum-=work[cur][i];
}
}
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d",&work[i][j]);
}
minn+=work[i][i];
}
dfs(0);
printf("%d",minn);
return 0;
}
POJ 1321 棋盘问题
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char a[10][10]; //记录棋盘位置
int vis[10]; //记录一列是否已经放过棋子
int n,k;
int total,m; //total 是放棋子的方案数 ,m是已放入棋盘的棋子数目
void DFS(int cur)
{
if(k==m)
{
total++;
return ;
}
if(cur>=n) //边界
return ;
for(int j=0; j<n; j++)
if(vis[j]==0 && a[cur][j]=='#') //判断条件
{
vis[j]=1; //标记
m++;
DFS(cur+1);
vis[j]=0; //取消回溯标记
m--;
}
DFS(cur+1); //第cur列可以放 ,也可以不放
}
int main()
{
int i,j;
while(scanf("%d%d",&n,&k)&&n!=-1&&k!=-1) //限制条件
{
total=0;
m=0;
for(i=0; i<n; i++)
scanf("%s",&a[i]);
memset(vis,0,sizeof(vis));
DFS(0);
printf("%d\n",total);
}
return 0;
}