最近从网上收集tsp问题实例,因为网上的格式较为复杂,于是进行了一些小的转换。从而成为简单的格式,用于我的实验代码输入。我的代码需要的格式是:先给出城市数N,然后列出N个 x y 坐标。转换的代码如下:包含一个转换程序transformOneProblem.cpp 和一个批量处理的python脚本。
1: #include<iostream>
2: #include<fstream>
3: #include<stdlib.h>
4:
5:
6: using namespace std;
7:
8: int main(int argc,char ** argv)
9: {
10: if(argc<2)
11: {
12: cout<<"error, you need paramete a file to transform"<<endl;
13: exit(0);
14: }
15: ifstream in;
16: in.open(argv[1]);
17:
18: int cityNum=0;
19:
20: int count=0;
21: char c;
22: string temp1,temp2,line;
23: while(count<5)
24: {
25: getline(in,line);
26: count++;
27: }
28:
29: in>>temp1;
30: in>>c;
31: in>>temp2;
32:
33: cityNum=atoi(temp2.c_str());
34:
35: count=0;
36: while(count<3)
37: {
38: getline(in,line);
39: cout<<line<<endl;
40: count++;
41: }
42:
43:
44: ofstream out;
45: string outname;
46: string app="_formated";
47: outname=argv[1]+app;
48: out.open(outname.c_str(),ofstream::out);
49:
50: out<<cityNum<<endl;
51:
52: int id,x,y,i;
53: i=0;
54: while(i<cityNum)
55: {
56: in>>id>>x>>y;
57: out<<x<<" "<<y<<endl;
58: cout<<x<<" "<<y<<endl;
59: i++;
60: }
61:
62: in>>temp1;
63: if(temp1!="EOF")
64: {
65: cout<<"error in transforming file "<<argv[1]<<endl;
66: }
67:
68: in.close();
69: out.close();
70:
71:
72: }
python脚本如下(主要是对多个文件进行批处理)
1: #!/bin/python
2: #coding=utf-8
3: import os
4: import sys
5:
6: #将allProblem.txt中的问题,用transformOneProblem进行formate。形成我们需要的格式的问题
7: def transform():
8: pro=[]
9: infile=open(r'allProblem.txt')
10: pro=infile.readlines();
11:
12: for p in pro:
13: print p
14: s=r"./transformOneProblem";
15: ns=s+" "+p
16: print ns
17: #print ns
18: #os.system("%s %s"("transformOneProblem",p))
19: os.system(ns)
20: print "exec "+ ns
21: print
22: #print "exec "+("%s %s"("transformOneProblem",p))
23:
24:
25:
26:
27:
28:
29: transform()
30: