#includestdafx.h#includemath.h#includetime.h#includeiostream#includefstreamusingnamespacestd;intc1=2;//加速因子intc2=2;//加速因子doublew=1;//惯性权重doubleWmax=1;//最大惯性权重doubleWmin=0.6;//最小惯性权重intKmax=110;//迭代次数intGdsCnt;//物资总数intconstDim=10;//粒子维数intconstPNum=50;//粒子个数intGBIndex=0;//最优粒子索引doublea=0.6;//适应度调整因子doubleb=0.5;//适应度调整因子intXup[Dim];//粒子位置上界数组intXdown[Dim]=;//粒子位置下界数组intValue[Dim];//初始急需度数组intVmax[Dim];//最大速度数组classPARTICLE;//申明粒子节点voidCheck(PARTICLE&,int);//约束函数voidInput(ifstream&);//输入变量voidInitial();//初始化相关变量doubleGetFit(PARTICLE&);//计算适应度voidCalculateFit();//计算适应度voidBirdsFly();//粒子飞翔voidRun(ofstream&,int=2000);//运行函数//微粒类classPARTICLE{public:intX[Dim];//微粒的坐标数组intXBest[Dim];//微粒的最好位置数组intV[Dim];//粒子速度数组doubleFit;//微粒适合度doubleFitBest;//微粒最好位置适合度};PARTICLEParr[PNum];//粒子数组intmain()//主函数{ofstreamoutf(out.txt);ifstreaminf(data.txt);//关联输入文件infGdsCnt;//输入物资总数Input(inf);Initial();Run(outf,100);system(pause);return0;}voidCheck(PARTICLE&p,intcount)//参数:p粒子对象,count物资数量{srand((unsigned)time(NULL));intsum=0;for(inti=0;iDim;i++){if(p.XXup){p.X=Xup;}elseif(p.XXdown){p.X=Xdown;}if(p.VVmax){p.V=Vmax;}elseif(p.V0){p.V=0;}sum+=p.X;}while(sumcount){p.X[rand()%Dim]--;sum=0;for(inti=0;iDim;i++){if(p.XXup){p.X=Xup;}elseif(p.XXdown){p.X=Xdown;}if(p.VVmax){p.V=Vmax;}elseif(p.V0){p.V=0;}sum+=p.X;}}}voidInput(ifstream&inf)//以inf为对象输入数据{for(inti=0;iDim;i++){infXup;}for(inti=0;iDim;i++){infValue;}}voidInitial()//初始化数据{GBIndex=0;srand((unsigned)time(NULL));//初始化随机函数发生器for(inti=0;iDim;i++){Vmax=(int)((Xup-Xdown)*0.035);}for(inti=0;i{for(intj=0;jDim;j++){Parr.X[j]=(int)(rand()/(double)RAND_MAX*(Xup[j]-Xdown[j])-Xdown[j]+0.5);Parr.XBest[j]=Parr.X[j];Parr.V[j]=(int)(rand()/(double)RAND_MAX*(Vmax[j]-Vmax[j]/2));}Parr.Fit=GetFit(Parr);Parr.FitBest=Parr.Fit;if(Parr.FitParr[GBIndex].Fit){GBIndex=i;}}}doubleGetFit(PARTICLE&p)//计算对象适应度{doublesum=0;for(inti=0;iDim;i++){for(intj=1;j=p.X;j++){sum+=(1-(j-1)*a/(Xup-b))*Value;}}returnsum;}voidCalculateFit()//计算数组内各粒子的适应度{for(inti=0;i{Parr.Fit=GetFit(Parr);}}voidBirdsFly()//粒子飞行寻找最优解{srand((unsigned)time(NULL));staticintk=10;w=Wmax-k*(Wmax-Wmin)/Kmax;k++;for(inti=0;i{for(intj=0;jDim;j++){Parr.V[j]=(int)(w*Parr.V[j])+(int)(c1*rand()/(double)RAND_MAX*(Parr.XBest[j]-Parr.X[j])+c2*rand()/(double)RAND_MAX*(Parr[GBIndex].XBest[j]-Parr.X[j]));}Check(Parr,GdsCnt);for(intj=0;jDim;j++){Parr.X[j]+=Parr.V[j];}Check(Parr,GdsCnt);}CalculateFit();for(inti=0;i{if(Parr.Fit=Parr.FitBest){Parr.FitBest=Parr.Fit;for(intj=0;jDim;j++){Parr.XBest[j]=Parr.X[j];}}}GBIndex=0;for(inti=0;i{if(Parr.FitBestParr[GBIndex].FitBest&&i!=GBIndex){GBIndex=i;}}}voidRun(ofstream&outf,intnum)//令粒子以规定次数num飞行{for(inti=0;inum;i++){BirdsFly();outf(i+1)endsfor(intj=0;jDim;j++){outf}outfendl;}coutDone!endl;}