[Explanations] luogu_P4042_ Knight game (dp + spfa

In the lower portion of sub-DAG is a graph Obviously dp, dp topological sort can be done, in the presence of the ring, I will not know why to use spfa dp

Main investigation of spfa understanding is deep, in fact, the process spfa is a dp process, especially $ if (d [y]> d [x] + w) d [y] = d [x] + w $ very much like a dp formula,

We take every possible update point other points to try to update other points, continue to search for possible updates other points of points in the process,

For this question, it can be updated every time a certain point, this point is likely to renew his father, and all his father into the queue for the next update all

But I'm still very, very shallow understanding spfa

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=200009;
const int maxm=1000009;
inline ll read(){
    ll ret=0,fix=1;char ch;
    while(!isdigit(ch=getchar()))fix=ch=='-'?-1:fix;
    do ret=(ret<<1)+(ret<<3)+ch-'0';
    while(isdigit(ch=getchar()));
    return fix*ret;
}
int n;
struct node{
    int v,nxt;
}e[maxm],e2[maxm];
int head[maxn],cnt,head2[maxn],cnt2;
inline void add(int u,int v){
    e[++cnt].v=v;e[cnt].nxt=head[u];head[u]=cnt;
}
inline void add2(int u,int v){
    e2[++cnt2].v=v;e2[cnt2].nxt=head2[u];head2[u]=cnt2;
}
ll d[maxn],s[maxn],k[maxn];
queue<int>q;
bool v[maxn];
void spfa(){
    for(int i=1;i<=n;i++)q.push(i),v[i]=1;
    while(!q.empty()){
        int x=q.front();q.pop();v[x]=0;
        ll sum=s[x];
        for(int i=head[x];i;i=e[i].nxt)sum+=d[e[i].v];
        if(d[x]>sum){
            d[x]=sum;
            for(int i=head2[x];i;i=e2[i].nxt){
                if(!v[e2[i].v])q.push(e2[i].v),v[e2[i].v]=1;
            }
        }
    }
}
int main(){
    n=read();
    for(int i=1,v,r;i<=n;i++){
        s[i]=read();k[i]=read();r=read();
        for(int j=1;j<=r;j++)
        v=read(),add(i,v),add2(v,i);
    }
    for(int i=1;i<=n;i++)d[i]=k[i];
    spfa();
    printf("%lld",d[1]);
}

 

Guess you like

Origin www.cnblogs.com/superminivan/p/11494267.html