ER随即图生成程序2012-07-1411:14:19|分类:复杂网络研究|举报|字号订阅#includeiostream#includevector#includelist#includeWindows.h#includetime.husingnamespacestd;vectorlistintg;//邻接表存储网络vectorfloatpp;//存放概率的向量intedge;structp_point{intx;inty;};vectorp_pointcon;//为了方便写入文件intcreate_random(intc_begin,intc_end){//产生从c_begin到c_end之间的任意正数,包括c_begin和c_endtime_tt;Sleep(500);srand((unsigned)time(&t));intkiss=rand()%(c_end-c_begin+1)+c_begin;returnkiss;}intcreate_random_also(intcc_begin,intcc_end){time_tt;Sleep(200);srand((unsigned)time(&t));intkiss=rand()%(cc_begin-cc_end+1)+cc_begin;returnkiss;}p_pointcreate_different(intdiff_begin,intdiff_end){//产生两个从diff_begin到diff_end之间的数,包括//包括diff_begin和diff_end,并且保证两者不同p_pointpc;pc.x=create_random(diff_begin,diff_end);intcp=0;do{cp=create_random_also(diff_begin,diff_end);}while(pc.x==cp);pc.y=cp;returnpc;}voidRead_python_file(intedge)//pp向量用来存放程序所需要的概率,从python文件中生成的,pp为全局变量{FILE*ptr;floata;ptr=fopen(random.txt,r);for(inti=0;iedge;i++){fscanf(ptr,%f,&a);pp.push_back(a);}}boolFind_in_network(inta,intb){//查找b是否已经和a相连接了,连接了返回true,反之返回falsefor(listint::iteratorit=g[a].begin();it!=g[a].end();++it){if((*it)==b)returntrue;}returnfalse;}voidCreate_ER_random(intN,floatp){//产生的概率如果比我手动输入的概率小的话就连接g.assign(N+1,listint());g[0].push_back(0);edge=p*N*(N-1)/2;couttheedgeofthenetworkis:edge;Read_python_file(65534);intii=0;//概率向量指示器intc=0;p_pointnode;inti=0;//节点指示器while(iedge){//在成功加入一个节点后,把i的值加1node=create_different(1,N);while(!Find_in_network(node.x,node.y)&&pp[ii]p&&iN+1){g[node.x].push_back(node.y);g[node.y].push_back(node.x);con.push_back(node);i++;c=ii;ii++;}if(Find_in_network(node.x,node.y)||pp[c]p){ii++;}if(ii=65535)coutoutofprobabilyrange,pleasetryagain,thankyouendl;}}voidShow_ERnetwork(intN){//此函数把邻接表中的元素输出到屏幕上coutendl;for(inti=1;i=N;++i){coutg[i]--;for(listint::iteratorit=g[i].begin();it!=g[i].end();++it)cout*it;coutendl;}}voidWrite_to_pajek_file(intN){//这个模块儿在后面的很多程序中都会用到,功能是把生成的网络写入到pajek软件中FILE*file;file=fopen(ERrandom.net,w);fprintf(file,%s%d\n,*Vertices,N);for(inti=1;i=N;i++){fprintf(file,%d\n,i);}fprintf(file,%s\n,*Arces);fprintf(file,%s\n,*Edges);for(vectorp_point::iteratorit=con.begin();it!=con.end();++it){fprintf(file,%d%d%d\n,(*it).x,(*it).y,1);fprintf(file,%d%d%d\n,(*it).y,(*it).x,1);}fclose(file);}voidWrige_to_txt_file(intn){FILE*file;file=fopen(network.txt,w);fprintf(file,%d\n,n);fprintf(file,%d\n,edge);for(vectorp_point::iteratorit=con.begin();it!=con.end();++it){fprintf(file,%d%d\n,(*it).x,(*it).y);}fclose(file);}voidmain(){intV_number;floatp_ER;coutpleaseenterthevertexnumber:endl;cinV_number;coutpleaseentertheprobability:endl;cinp_ER;Create_ER_random(V_number,p_ER);Write_to_pajek_file(V_number);Show_ERnetwork(V_number);system(pause);}random.pyimportrandomimportosimportstringf=open('random.txt','w')foriinrange(1000000):j=random.random()f.write(str(j))f.write('\n')f.close()