[Shortest path] poj 2387

Source: Internet
Author: User

#include <iostream>#include <stdlib.h>#include <limits.h>#include <string.h>using namespace std;int map[1010][1010];int dis[1010];int n,pos,sum;void init(){ for(int i=0; i<1001; i++) {  for(int k=0; k<1001; k++)   map[i][k] = INT_MAX;  map[i][i] = 0; } for(int i=0; i<1001; i++)  dis[i] = INT_MAX; sum = 0;}void Dijkstra(){ int used[1010]; memset(used,0,sizeof(used)); int now = pos; dis[now] = 0; used[now] = 1; for(int i=0; i<n; i++) {  for(int k=1; k<=n; k++)   if( map[now][k] != INT_MAX && dis[now] + map[now][k] < dis[k] )    dis[k] = dis[now] + map[now][k];  int min = INT_MAX;  for(int k=1; k<=n; k++)   if( dis[k] < min && !used[k] )    min = dis[now = k];  used[now] = 1; }}int main(){ int from,to,len,t; init(); cin >> t >> n; pos = n; for(int i=1; i<=t; i++) {  cin >> from >> to >> len;  if( len < map[from][to] )   map[from][to] = map[to][from] = len; } Dijkstra(); cout << dis[1] << endl;return 0;}   #include<iostream>using namespace std;#define MAX 1005const int oo=10000000;int dist[MAX][MAX];int close[MAX];bool used[MAX];int main(){    int N,T,i,j;    int s,e,len;    scanf("%d%d",&T,&N);    memset(dist,0x7f,sizeof(dist));    memset(used,false,sizeof(used));    memset(close,0x7f,sizeof(close));    for(i=1;i<=T;i++)    {        scanf("%d%d%d",&s,&e,&len);        if(dist[s][e]>len)            dist[s][e]=dist[e][s]=len;    }    for(i=2;i<=N;i++)    {        close[i]=dist[1][i];    }    used[1]=true;    for(i=2;i<=N;i++)    {        int min=0;int mlen=oo;        for(j=2;j<=N;j++)        {            if(!used[j]&&close[j]<mlen)            {                min=j,mlen=close[j];            }        }        used[min]=true;        for(j=2;j<=N;j++)        {            if(!used[j]&&dist[min][j]<oo)            {                int temp=dist[min][j]+close[min];                if(temp<close[j])                    close[j]=temp;            }        }    }    printf("%d\n",close[N]);    return 0;}

 

[Shortest path] poj 2387

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.