noip2009 optimal trade - spfa

Topic description: There is a graph with a total of n nodes and m edges, to ensure that there is a path from node 1 to node n, find two nodes on a path (denoted as p, q - in this path, p is before q ) to maximize the difference between the weights of p and q;

 

Konjac idea: spfa finds the largest difference between (p and q)

        In the process of spfa, the first element of each team is recorded as x, and the node connected to it is recorded as y, then for each node y, its optimal solution (the largest difference) can only be updated by two quantities:

      1. The optimal solution of x;

      2. The weight of node y - the weight of node x

The spicy chicken code presents:

#include<bits/stdc++.h>
using namespace std;
struct Node{
    int to,next;
}e[2000005];

int pr[100005],cnt;
int n,m;
int head[500005],d[100005];
bool v[100005];

queue<int> q;


void addedge(int x,int y)
{
    e [ ++ cnt] .to = y;
    e[cnt].next=head[x];
    head[x]=cnt;
}

void spfa()
{
    memset(d,-1,sizeof(d));
    q.push(1);
    v[1]=true;
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        v[x]=false;
        for(int i=head[x];i;i=e[i].next)
        {
            int u=e[i].to,f=1;
            if(d[u]==-1||d[u]<pr[u]-pr[x])
            {
                if (pr[u]-pr[x]> 0 )d[u]=pr[u]- pr[x];
                f=0;
            }
            if(d[u]<d[x])
            {
                d[u]=d[x];
                f=0;
            }    
            if(!f)
            {
                q.push(u);
                v[u]=true;
            }
        }
    }
}

intmain ()
{
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%d",&pr[i]);
    for(int i=1;i<=m;i++)
    {
        int x,y,q;
        scanf("%d %d %d",&x,&y,&q);
        addedge(x,y);
        if(q==2)addedge(y,x);
    }
    sppa();
    if(d[n]==-1)printf("0");
    else        printf("%d\n",d[n]);
    return 0;
}

 


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325384710&siteId=291194637