1、using namespace std;typedef long long LL;const double MAX_VAL = (double)1e18;const int MAX_GEN = 30;/最大迭代次数const int MAX_SCALE = 3000;/最大种群规模const int MAX_CITY = 20 + 2;/最大城市数const double W_VAL = 0.729;/struct SO int x, y; SO() SO(int x, int y): x(x), y(y);struct Point double x, y; Point() Point(int
2、 x, int y):x(x), y(y); void read() scanf(%lf%lf, &x, &y); inline int randomI(int x) return rand()%x;inline double randomD() return (double)rand()/RAND_MAX;inline double getDist(Point a, Point b) return sqrt(a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);struct PSO double w; int scale; int city
3、Num; int nowGen;/当前代数 int maxGen;/迭代次数 int bestNum; int bestGen;/最佳出现代数 double distMAX_CITYMAX_CITY; int oPopMAX_SCALEMAX_CITY;/粒子群 double fitnessMAX_SCALE;/种群适应度,表示种群中各个个体的适应度 vector listVMAX_SCALE;/ 每科粒子的初始交换序列 int PdMAX_SCALEMAX_CITY;/一颗粒子历代中出现最好的解, double vPdMAX_SCALE;/解的评价值 int PgdMAX_CITY;/ 整个
4、粒子群经历过的的最好的解,每个粒子都能记住自己搜索到的最好解 double vPgd;/ 最好的解的评价值 PSO() PSO(int s, int c, int mG, double ww, double dMAX_CITYMAX_CITY) scale = s; cityNum = c; maxGen = mG; w = ww; for (int i = 0; i cityNum; i+) for (int j = 0; j j+) distij = dij; void copyArray(double a, double b, int n) n; i+) ai = bi; void co
5、pyArray(int a, int b, int n) void init() nowGen = 0; scale; ) int x = randomI(cityNum); int r; for (r = 0; r j; r+) if (x = oPopir) break; if (r = j) oPopij = x;/ cout oPopij ; j+; endl; : int vn = randomI(cityNum) + 1; vn; int y = randomI(cityNum); while (x = y) y = randomI(cityNum); SO so(x, y); l
6、istVi.push_back(so); so.x * so.y fitnessi) vPgd = fitnessi; bestNum = i; copyArray(Pgd, oPopbestNum, cityNum); double getVal(int x) double ret = 0; int xx = oPopxi % cityNum; int yy = oPopx(i + 1) % cityNum; ret += distxxyy; return ret; void getFitness() fitnessi = getVal(i); void UpdateVal() int j
7、= 0; double vj = fitness0; if (vPdi /? if (vj vj = fitnessi; j = i; if (vj vPgd) bestGen = nowGen; bestNum = j; vPgd = vj; copyArray(Pgd, oPopj, cityNum); void changeTo(int a, vector v)/ int vn = v.size(); int x = vi.x, y = vi.y; swap(ax, ay); minus(int a, int b)/ int cMAX_CITY, dMAX_CITY; i+) di =
8、bi; i+) cai = i; v; SO s; if (di != ai) s.x = i, s.y = cai; swap(ds.x, ds.y); v.push_back(s); return v; void addTo(vector &v, vector a, int vn) v.push_back(ai); / Vii=wVi+ra(Pid-Xid)+rb(Pgd-Xid) void evolution() for (int ig = 0; ig maxGen; ig+) nowGen = ig + 1;/nowGen for (int is = 0; is is+) if (is
9、 = bestNum) continue; v.clear(); int lvn = w * listVis.size(); addTo(v, listVis, lvn); a = minus(Pdis, oPopis); int an = randomD() * a.size(); addTo(v, a, an); b = minus(Pgd, oPopis); int bn = randomD() * b.size(); addTo(v, b, bn); listVis = v; changeTo(oPopis, listVis); listVis.size() UpdateVal(); void solve() init(); evolution(); printf(answer %lf:n, vPgd);solution n); if (i) printf(%dn, Pgdi);
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1