//http://www.baidu.com/link?url=nmlOGJqjJ4zBBpC8yDF8xDhotiai_VVkECoEgoAP2tqqPI27THAphBMwAzLp68yFL6mX0lOyqYlp1EgxPP7
//算法源自上面链接。
#include
#include
#include
#include
#include
int GroupScale;
int ProblemScale;
int CrossoverNum;
int MutationNum;
int MaxGeneration=10000;
double CrossoverRate=0.8;
double MutationRate=0.001;
int * * InitPopulation()
{
int i,j;
int **a=new int*[GroupScale];
for(i=0;i
a[i]=new int[ProblemScale];
}
srand((unsigned)time(NULL));
for(i=0;i
for(j=0;j
a[i][j]=ProblemScale*rand()/(RAND_MAX+1);
}
}
return a;
}
void main()
{
clock_t start,finish;
int i,j,k,n,min,temp;
int **queen,*fitness,*selection;
double rate,*value,total,duration;
printf("请输入种群规模和问题规模:\n");
scanf("%d%d",&GroupScale,&ProblemScale);
CrossoverNum=(int)(GroupScale * CrossoverRate);
MutationNum=(int)(GroupScale * MutationRate);
if(CrossoverNum%2==1) CrossoverNum++;
fitness=new int[GroupScale];
value=new double[GroupScale];
selection=new int[CrossoverNum];
while(true)
{
start=clock();
//(1)创建初始群体
queen = InitPopulation();
while(MaxGeneration--)
{
//(2)计算群体中个体适应度
total=0;
min=INT_MAX;
for(k=0;k
fitness[k]=0;
for(i=0;i
for(j=i+1;j
if(queen[k][i]==queen[k][j]) fitness[k]++;
if(abs(queen[k][i]-queen[k][j])==j-i) fitness[k]++;
}
}
if(fitness[k]
n=k;
min=fitness[k];
}
}
//(3)评估适应度
if(min==0) break;
//(4)根据适应度选择个体
for(k=0;k
value[k]=1.0/fitness[k];
total+=value[k];
}
for(k=0;k
value[k]/=total;
if(k!=0) value[k]+=value[k-1];
}
//(用赌盘选择法选择个体)
for(i=0;i
rate=rand()*1.0/(RAND_MAX+1);
if(rate
{
for(j=1;j
selection[i]=j;
break;
}
}
}
//(5)被选择个体进行交叉繁殖
for(i=0;i
//随机选择交叉点
k=ProblemScale*rand()/(RAND_MAX+1);
for(j=k;j
temp=queen[selection[i]][j];
queen[selection[i]][j]=queen[selection[i+1]][j];
queen[selection[i+1]][j]=temp;
}
}
//(6)繁殖过程中引入变异机制
for(k=0;k
i=GroupScale*rand()/(RAND_MAX+1);
j=ProblemScale*rand()/(RAND_MAX+1);
queen[i][j]=ProblemScale*rand()/(RAND_MAX+1);
}
}
finish=clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
if(min==0)
{
printf("\n");
for(i=0;i
for(j=0;j
if(queen[n][i]==j) printf("■");
else printf("□");//★☆●○
}
printf("\n");
}
printf("It costs %.3lf seconds.\n",duration);
}
else
printf("\n%.3lf seconds has elapsed and no one is fit.\n",duration);
printf("\nTry Again ?\n1)Yeah.\t2)Exit.[ ]\b\b");
scanf("%d",&k);
if(k==2) break;
}
return;
}