图论相关算法汇总(二)

一. 最小生成树(Kruscal算法)

#include "iostream"
#include "cstdlib"
#include "cstring"
#include "cstdio"
#define N 10000
#define M 100000
using namespace std;

struct edge //边集 
{
    int start;  //起点 
    int end;  //终点 
    int weight;  //权值 
}e[M];  
int n,m; //结点数,边数 
int cmp(const void *a,const void *b);//按升序排列
void kruscal(int *sum);

int main(){
	//freopen("a.txt","r",stdin);
    int i,sum;
  	cin>>n>>m;
    for(i=0;i>e[i].start>>e[i].end>>e[i].weight;//输入每条边的权值
    kruscal(&sum);
    cout<weight - ((struct edge*)b)->weight ;
}
void kruscal(int *sum){
	int i,k,g,x[N],num;
	for(i=1;i<=n;i++)
        x[i]=i;
    qsort(e,m,sizeof(e[0]),cmp);  //给边排序 
    *sum=num=0;
    for(i=0;i

二. 最小生成树(Prim算法)

#include "iostream"
#include "cstdio"
#define M 100000  //最大边数 
#define N 10000  //最大结点数 
#define INF 100000 
using namespace std;

struct edge{ //边集 
    int start;  //起点 
    int end;    //终点 
    int weight;  //权值 
}e[M];  
int n,m;   //定点数和边数 
int getWeight(int v,int w); //求w到v距离
void prim(int fa[],int *sum);

int main(void)
{
	//freopen("a.txt","r",stdin);
	int sum;    //最小生成树总长 
	int i; 
	cin>>n>>m;
	for(i=0; i>e[i].start>>e[i].end>>e[i].weight; 
   	int fa[N];
   	prim(fa,&sum);
   	cout<getWeight(k,j) && d[j] != 0){
                d[j] = getWeight(k,j); 
                fa[j] = k;
            }
    }
}

三. 单源最短路径(Dijkstra算法)

#include"iostream"
#include"cstdlib"
#include"cstdio"
#include"cstring"
#define N 100   //顶点最大数 
#define M 10000   //边最大数 
#define INF 1000000  //两点之间没有路径 
using namespace std;

typedef struct node  //边节点
{  
   int adjvex;
   int weight;  
   node* next;  
}EdgeNode;  
EdgeNode * node[N+1];  //node[i] 表示顶点i的第一个邻接点地址,下标从 1 开始 
int D[N+1];       // 保存最短路径长度 
int p[N+1][N+1];   // 路径
int final[N+1];  // 若final[i]  =  1则说明 顶点vi已在集合S中
int n,m;      //顶点数和边数 
void Dijkstra(int v);   // DijKstra
int getWeight(int v,int w);  //得到v到w的距离 

int main()  
{  
	//freopen("a.txt","r",stdin);
	int i; 
	EdgeNode *s;
	cin>>n>>m;  
	for(i=1; i>x>>y>>z;
		s = (EdgeNode*)malloc(sizeof(EdgeNode)); 
		s->adjvex = y;       //插入表头 
		s->weight = z;
		s->next = node[x];
		node[x] = s;
		s = (EdgeNode*)malloc(sizeof(EdgeNode)); //无向图,若为有向图则去掉下面的 
		s->adjvex = x;
		s->weight = z;
		s->next = node[y];
		node[y] = s;
	} 
	int v0=1; 
	Dijkstra(v0);
	for(i=1;i<=n;i++){
		cout<"<adjvex==w)
			return p->weight;
		p=p->next;
	} 
	return INF;
} 



你可能感兴趣的:(算法)