(这是我很久之前写的一个程序,目前博客上还没有什么文章,就算充个数把)
本程序的问题描述可参见:Balance puzzle,或者也可以阅读我之前写的一个PPT。
头文件balance.h如下:
/************************************************************************************/
/* This demo implements the coding method for soving n coins problem */
/* No Copyrights! Feel free to copy it! */
/*----------------------------------------------------------------------------------*/
/*Algorithm: */
/*1. Violence search the solution for 3<=n<=12 */
/*2. Use the induction steps in the proof to get the following solution */
/************************************************************************************/#include<stdio.h>
#include<malloc.h>
#include<string.h>#define MAX 100;//k is no more than 100typedef struct set{int n;char * * node;
}SET;void convert(char * set[],int n,int k);
int thresh(int k);
SET * searchT(int n,int k,char * a);
SET * search(int n,int k);
void show(int k,bool state,SET * a);
bool check(SET * a);
搜索程序:
#include"balance.h"char * s1[3]={"01","20","12"};
char * s2[4]={"001","010","220","102"};
char * s3[5]={"001","010","220","012","120"};
char * s4[6]={"001","010","022","110","202","021"};
char * s5[7]={"001","010","011","220","202","120","102"};
char * s6[8]={"001","010","011","220","202","012","121","122"};
char * s7[9]={"001","010","011","220","202","120","201","112","122"};
char * s8[10]={"001","010","011","220","202","012","120","102","221","100"};
char * s9[11]={"001","010","111","011","220","202","120","102","221","212","122"};
char * s10[12]={"001","010","111","011","220","202","012","120","102","221","122","200"};/*calculate the threshold (3^k-3)/2*/
int thresh(int k)
{int tmp=1;for(int i=0;i<k;i++)tmp=tmp*3;return (tmp-3)/2;
}/*put k char 'a' ahead of a1*/
char * putch(char a,int k,char * a1)
{int n=strlen(a1);char * result;result=(char *)malloc(n+k+1);for(int i=0;i<n+k;i++){if(i<k)*(result+i)=a;else*(result+i)=*(a1+i-k);}*(result+n+k)='