HDU 1016 Prime Ring Problem 搜索题


  
    
#include<stdio.h>

#include<string.h>

#include <iostream>

using namespace std; int N; int prime[12]={2,3,5,7,11,13,17,19,23,29,31,37}; int ring[25]; int visited[25]; int search(int low ,int high,int x) { if(low>high)return 0; int mid=(low+high)>>1; if(x==prime[mid])return mid; else if(x>prime[mid]) { return search(mid+1,high,x); } return search(low,mid-1,x); } void DFS(int index,int primNum) { int i; if(primNum==N&&search(1,11,index+1)) { for( i=1;i<N;i++) {

            printf("%d ",ring[i]); }

        printf("%d\n",ring[N]); return ; } for(i=1;i<=N;i++) { if(!visited[i]&&((index&1)!=(i&1))&& search(1,11,index+i)) {

            visited[i]=1;

            ring[primNum+1]=i;

            DFS(i,primNum+1);

            visited[i]=0;

            ring[primNum+1]=0; } } } int main() { int cases=0; while(scanf("%d",&N)!=EOF) {

        cases++;

        memset(ring,0,sizeof(ring));

        memset(visited,0,sizeof(visited));

        printf("Case %d:\n",cases);

        visited[1]=1;

        ring[1]=1;

        DFS(1,1);

        printf("\n"); } return 0; }

你可能感兴趣的:(Prim)