Solving tsp problem with genetic algorithm

Source: Internet
Author: User
Tags chr

On genetic algorithm: https://www.cnblogs.com/AKMer/p/9479890.html

Description

\ (mzf\)On the lookout for\ (oxy\)and accidentally bumped into the great Lord after the journey.\ (fater\)。
The great Lord looked at\ (mzf\)The fate, the heart of Mercy, will give\ (mzf\)And make a chance to exchange with yourself.
This exchange is like this:
Because\ (oxy\)I do not know at the ends of the Earth\ (mzf\)It's too hard to find it. So the great Lord is willing to\ (mzf\)And\ (oxy\)and throw it into a maze (\ (n\)The full graph of the dots), but\ (oxy\)At which point is unknown.
\ (mzf\)Initially in\ (1\)Number points.\ (1\)There is a maze exit on the point, and opening the exit requires traversing the entire map to get the keys on all points.\ (mzf\)To think of your own thoughts and nights\ (oxy\)It is necessary to traverse all points from the unknown point in the depths of the maze. But the great Lord is not willing to help.\ (mzf\), he said that if\ (mzf\)Repeat through a point or walk the distance is not the shortest ring then he and\ (oxy\)Will never escape from the maze.
\ (mzf\)See\ (oxy\), regardless of the 3,721 promised the great lord. Before going in, the great Lord gave him a map and then\ (mzf\)Threw it into the maze and closed the entrance.
\ (mzf\)In the maze of darkness only to understand, oneself although is\ (oier\), but their\ (computer\)Seems to have been confiscated by the great Lord. Thus, as the same\ (oier\)Friend, he called to tell you about it and wanted you to help him. He gave you the map in the form of a matrix. Because he really misses\ (oxy\)Out, but he's too embarrassed to be too troublesome for you, so he wants you to be in\ (1s\)Help him figure out the shortest path. As long as you tell him the right answer, the person will tell him the best way to go.

Input

Enter Total \ (n+1\) Line
First line one number \ (n\)
The distance between the next \ (n\) order matrix,\ (dis[i][j]\) record \ (i,j\)

Output

Output only one line
A number representing the shortest length of the Hamilton Ring

Sample Input

4
0 1 2 3
1 0 2 3
2 2 0 3
3 3 3 0

Sample Output

9

\ (n\leqslant100,dis[i][j]\leqslant100000\)

I made it myself. Data: Https://files.cnblogs.com/files/AKMer/TSP.zip
As a result of the search run slowly so only made the \ (n\leqslant12\) data

First of all, the title means you need to find the length of the shortest Hamiltonian ring in a non-direction complete graph.

For this problem, the estimation function can be set to a longest ring length minus the length of the ring represented by the current chromosome, and the shorter the ring length, the higher the adaptability.

Then the swap operation is going to make some improvements. Because direct swapping causes a certain point to recur in a chromosome (which causes \ (mzf\) and \ (oxy\) to escape from the maze!! )。 So we switched between strings and strings to exchange two positions on a chromosome, and the mutation was done together.

It's done. If it is a question of the number of genetic algebra and mutation can be set a little more, if you want to cheat on the traditional problem remember not to set too high cause \ (tle\).

First \ (srand (0) \) mad \ (wa\) not only:

Is that all you can do? No!
Then I \ (srand\) our initials on \ (a\) off hahaha

Time complexity:\ (O (European) \)
Space complexity:\ (O (n) \)

The code is as follows:

#include <ctime> #include <cstdio> #include <cstring> #include <algorithm>using namespace std; const int Inf=10000005;const int Maxn=105;int dis[maxn][maxn];//dis storage distance int f[maxn],f1[maxn],g[maxn];//f Storage Fitness function, F1 cache F, The minimum length of n,low=inf,mx_f,tim,chr_cnt=100;//low in the current population is selected several times under G-Deterministic selection method, and the number of generations of Tim Deposit low is constant, and the CHR_CNT chromosome count is Mx_f, and the longest ring length int of the current population is stored.    Read () {int X=0,f=1;char ch=getchar (); for (;ch< ' 0 ' | |    Ch> ' 9 '; Ch=getchar ()) if (ch== '-') f=-1;    for (; ch>= ' 0 ' &&ch<= ' 9 '; Ch=getchar ()) x=x*10+ch-' 0 '; return x*f;} Fast read int random (int limit) {return rand ()%limit;}        Rand a [0,limit] range of number struct chromosome {int gene[maxn];//the order of points on the Save Ring Int calc () {int res=0;        for (int i=2;i<=n;i++) res+=dis[gene[i-1]][gene[i]];            Return res+dis[gene[n]][gene[1]];//the Edge}//on the accumulated ring in turn calculates the fitness function void initialization () {for (int i=1;i<=n;i++)        Gene[i]=i;    Random_shuffle (gene+1,gene+n+1); }//Initialize}CHR[MAXN],NEW_CHR[MAXN],ANS;//CHR Current population, NEW_CHR save the next generationGroup, ans Save scheme, finally used for statistical answer void Select () {//select for (int i=1;i<=chr_cnt;i++) {f[i]=chr[i].calc ();//Calculate Shortest Path Mx_f=max (        Mx_f,f[i]);            if (f[i]<low) {low=f[i],tim=0; ans=chr[i];//Update Global Answer if low is updated}} tim++;int res=0,cnt=0;//res Total Fitness, CNT storage next generation chromosome number for (int i=1;i<=chr_cnt;i+ +) f[i]=mx_f-f[i]+1,res+=f[i];//Update Fitness, add to res for (int i=1;i<=chr_cnt;i++) G[I]=1.0*F[I]/RES*CHR_CNT,F1    [i]=f[i],cnt+=g[i];//calculate g[i], the F cache to F1 while (cnt<chr_cnt) g[random (chr_cnt) +1]++,cnt++;//not select Full to continue to choose cnt=0;            for (int. i=1;i<=chr_cnt;i++) {for (int j=1;j<=g[i];j++) {new_chr[++cnt]=chr[i];        f[cnt]=f1[i];//Synchronization Update Fitness if (cnt==chr_cnt) break; } if (cnt==chr_cnt) break;//full no}//simulation selection process for (int i=1;i<=chr_cnt;i++) chr[i]=new_chr[i];//update Chr}vo ID variety () {///mutation for (int i=1;i<=500*chr_cnt;i++) {////////////////////////U=random (CHR_CNT) +1,l=random (n) +1,r=ra Ndom (n) +1;//u is the chromosome that is about to mutate,L and R are the positions to be exchanged chromosome tmp=chr[u];swap (tmp.gene[l],tmp.gene[r]);            int Res=tmp.calc ();//tmp cache mutated chromosome if (Res<chr[u].calc ()) {//If the compilation is better after the mutation chr[u]=tmp;        f[u]=mx_f-res;//update chromosome and fitness}}}void genetic () {while (1) {select ();    if (tim>200) return;//more than 200 generations unchanged even if the correct variety ();    }//Genetic Process}int main () {srand (' o ' + ' x ' + ' y ' + ' m ' + ' Z ' + ' f ');//her name is oxy, I am mzf n=read (); for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) dis[i][j]=read ();//read in for (int i=1;i<=chr_cnt;i++ ) Chr[i]. initialization ();//Initialize ancestor population genetic ();//Genetic printf ("%d\n", Ans.calc ());//output return 0;}

Solving tsp problems with genetic algorithms

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.