POJ-3268 Silver Cow Party Problem Solution Report (dijkstra Finds the Shortest Path of Single Source Starting and Single Source Ending respectively)

Main idea of the title:

Main idea: Give you a digraph, n (1000) points m (100,000) path let you find the maximum value of each point to point x and return to his own shortest path.

Analysis:

Using dijkstra algorithm, the shortest path from each point to point X and the shortest path from point x to each point can be obtained respectively.
Note that if - 1 is used to indicate that the road is not clear, then the code implementation process must consider many situations.

#include<iostream>
#include<string.h>
#include<math.h>
#define inf 0x3f3f3f3f

using namespace std;

int n,m,x;
int map[1050][1050];
int dis[1050]={0};
int bac[1050]={0};

void my_dijkstra()
{
    int book[1050]={0};
    for(int i=1;i<=n;i++)
    {
        dis[i]=map[i][x];
    }
    for(int i=1;i<n;i++)
    {
        int min=inf;
        int u;
        for(int j=1;j<=n;j++)
        {
            if(book[j]==1)continue;
            if(dis[j]==-1)continue;
            if(dis[j]<min)
            {
                min=dis[j];
                u=j;
            }
        }
        book[u]=1;
        for(int j=1;j<=n;j++)
        {
            if(map[j][u]==-1)continue;
            if(dis[j]>min+map[j][u]||dis[j]==-1)
            {
                dis[j]=min+map[j][u];
            }
        }
    }
}

void my_dijkstra_gai()
{
    int book[1050]={0};
    for(int i=1;i<=n;i++)
    {
        bac[i]=map[x][i];
    }
    for(int i=1;i<n;i++)
    {
        int min=inf;
        int u;
        for(int j=1;j<=n;j++)
        {
            if(book[j]==1)continue;
            if(bac[j]==-1)continue;
            if(bac[j]<min)
            {
                min=bac[j];
                u=j;
            }
        }
        book[u]=1;
        for(int j=1;j<=n;j++)
        {
            if(map[u][j]==-1)continue;
            if(bac[j]>min+map[u][j]||bac[j]==-1)
            {
                bac[j]=min+map[u][j];
            }
        }
    }
}

int main()
{
    while(cin>>n>>m>>x)
    {
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                map[i][j]=-1;
                if(i==j)map[i][j]=0;
            }
        }
        for(int i=1;i<=m;i++)
        {
            int ls,le,lv;
            cin>>ls>>le>>lv;
            map[ls][le]=lv;
        }
        my_dijkstra();
        my_dijkstra_gai();
        int max=0;
        for(int i=1;i<=n;i++)
        {
            if(dis[i]==-1||bac[i]==-1)continue;
            if(max<dis[i]+bac[i])
            {
                max=dis[i]+bac[i];
            }
        }
        /*for(int i=1;i<=n;i++)cout<<dis[i];
        cout<<endl;
        for(int i=1;i<=n;i++)cout<<bac[i];
        cout<<endl; */
        cout<<max<<endl;
    }
}

Posted by bsamson on Wed, 13 Feb 2019 20:51:18 -0800