点的最短路径

FLOYD

    for (int k=1;k<=n;k++)
        for (int i=1;i<=n;i++)
            for (int j=1;j<=n;j++)
                    if (f[i][j]>f[i][k]+f[k][j]) f[i][j]=f[i][k]+f[k][j];

dj

    memset(book,0,sizeof(book));
    memset(dis,127,sizeof(dis));
    dis[s]=0;
    while (true){
        int v=-1;
        for (int i=1;i<=n;i++){
            if (!book[i]&&(v==-1||dis[i]if (v==-1) break;
        book[v]=1;
        for (int i=1;i<=n;i++)
            dis[i]=min(dis[i],dis[v]+f[v][i]);
    }

‘DJ邻接表+队列优化’

#include
#include
#include
#include
#include

using namespace std;

double f[1000][1000],dis[1010];
int n,m,s,t;

struct node{
    int x;
    int y;
}map[110];

struct edge {
    int to;
    double w;
};

vector g[500];

typedef pair<int, int> P;
double dist(node p1,node p2){
    return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}

int main(){
    cin>>n;
    for (int i=1;i<=n;i++)  
        cin>>map[i].x>>map[i].y;
    cin>>m;

    for (int i=1;i<=m;i++){
        edge ed;    
        int x,y;
        cin>>x>>y;
        ed.to=y;
        ed.w=dist(map[x],map[y]);
        g[x].push_back(ed);
        ed.to=x;
        g[y].push_back(ed);     
    }

    cin>>s>>t;

    memset(dis,127,sizeof(dis));
    priority_queuevector

,greater

> pq; dis[s]=0; pq.push(P(0,s)); while (!pq.empty()){ P tmp=pq.top(); pq.pop(); int v=tmp.second; if (dis[v]continue; for (int i=0;iif (dis[v]+ed.wprintf("%.2lf",dis[t]); }

bellman-ford

#include
#include
#include
#include
using namespace std;

const double INF = 10000000;
double dis[1010];
struct node{
    int x;
    int y;
}map[1100];

struct edge{
    int lai,qu;
    double w;
}ed[10100];
double dist(node p1,node p2){
    return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}

int main(){
    int n,m;
    cin>>n;
    for (int i=1;i<=n;i++)  cin>>map[i].x>>map[i].y;
    cin>>m;
    int k=1;
    for (int i=1;i<=m;i++){
        int x,y;
        cin>>x>>y;
        ed[k].lai=x;
        ed[k].qu=y;
        ed[k].w=dist(map[x],map[y]);
        k++;
        ed[k].lai=y;
        ed[k].qu=x;
        ed[k].w=ed[k-1].w;
        k++;
    }
    int s,t;
    cin>>s>>t;
    fill(dis,dis+n+1,INF);
    dis[s]=0;
    while (true){
        bool book=false;
        for (int i=1;i<=2*m;i++){
            edge e=ed[i];
            if (dis[e.lai]!= INF &&dis[e.qu]>dis[e.lai]+e.w){
            dis[e.qu]=dis[e.lai]+e.w;
            book=true;
        }
    }
    if (!book) break;
    }
    printf("%.2lf",dis[t]);
}`

你可能感兴趣的:(图论)