最近在使用遗传算法处理图的最优化路径。因为基因位由路径节点本身表示,在随机生成新的路径点的时候有可能会与先前的重复,造成闭环,这种情况应该删去该闭环,仅保留开始的一位。其中应用了一些小技巧,记录如下:
#include<vector>
#include<iostream>
#include<string>
using namespace std;
int main(){
vector<int> vec = {
0,
2,
3 ,
7 ,
8 ,
4,
8,
14 ,
15 ,
14 ,
13 ,
17 };
show(vec,
"BeforeDeleteCycles:");
DeleteCycles(vec);
show(vec,
"AfterDeleteCycles:");
}
void DeleteCycles(
std::
vector<int> vec){
int dupIndex_first, dupIndex_end;
for (
unsigned int i =
0; i < vec.size(); i++) {
dupIndex_end = i ;
for (
unsigned int j = i +
1; j < vec.size(); j++) {
if (vec[i] == vec[j]) {
dupIndex_end = j;
}
}
if (dupIndex_end > i){
vec.erase(vec.begin() + i +
1, vec.begin() + dupIndex_end +
1);
}
}
void show(
std::
vector<int> vec,
std::
string debug_name){
cout <<
"Debug:"<<debug_name<<endl;
for (
unsigned int i =
0; i != vec.size(); i++) {
cout << i <<
" " << vec[i] << endl;
}
cout << endl;
}
在此感谢雷神提出的建议!