USACO 1.5 Checker Challenge

回溯法,要利用解的对称特性来优化

#include <stdio.h>
#include 
<string.h>
#include 
<stdlib.h>

typedef 
int bool;
#define true 1
#define false 0 

int pos[13];
bool row_status[13];
int total = 0;
int n;

void backtracing(int depth);

void solve()
{

#ifndef _DEBUG
    freopen(
"checker.in","r",stdin);
    freopen(
"checker.out","w",stdout);
#endif

    memset(pos,
0,sizeof(pos)); 
    memset(row_status,
0,sizeof(row_status));

    scanf(
"%d",&n);

    
int p; 
    
int t = n/2;
    
for(p=0;p<t;++p){
        pos[
0= p;
        row_status[p] 
= true;
        backtracing(
1);
        row_status[p] 
= false;
    }

    
if(total<3){
        
for(p=t;p<n;++p){
            pos[
0= p;
            row_status[p] 
= true;
            backtracing(
1);
            row_status[p] 
= false;
           }
    }
else{
        total
+=total;
        
if(n%2!=0){
            pos[
0]=t;
            row_status[t] 
= true;
            backtracing(
1);
            row_status[t] 
= false;
        }
    }

    printf(
"%d\n",total);
}

bool isok(int depth,int p)
{
    
int i;

    
if(row_status[p])
        
return false;

    
for(i=0;i<depth;++i){
        
if(abs(pos[i]-p)==abs(depth-i) )
            
return false;
    }

    
return true;
}

void backtracing(int depth)
{
    
if(depth==n){
       total
++
       
if(total<=3){
           
int i;
           
for(i=0;i<n;++i){
               
if(i==0){
                    printf(
"%d",pos[i]+1);
               }
else{
                    printf(
" %d",pos[i]+1); 
               }
           }
           printf(
"\n");
       }
    }
else{
        
int i;
        
for(i=0;i<n;++i){
            
if( isok(depth,i) ){
                pos[depth] 
= i;
                row_status[i]
=true;
                backtracing(depth
+1);
                row_status[i]
=false;
            }
        }
    }
}

int main(int argc,char *argv[])
{
  solve();
  
return 0;
}


posted on 2009-06-16 21:33 YZY 阅读(935) 评论(0)  编辑 收藏 引用 所属分类: AlgorithmUSACO


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2009年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

统计

常用链接

留言簿(2)

随笔分类

随笔档案

搜索

积分与排名

最新评论

阅读排行榜