LUOGU P4042 [AHOI2014/JSOI2014]骑士游戏 (spfa+dp)

传送门

解题思路

  首先设(f[x])表示消灭(x)的最小花费,那么转移方程就是 (f[x]=min(f[x],sum f[son[x]] +s[x])),如果这个转移是一个有向无环图,那么就直接拿拓扑序转移就行了。但这个并不是,存在环,所以要用(spfa)进行反复松弛,具体来说就是先将所有入队,每次取出队头,看能否被儿子们更新,如果更新,就把他的父亲再次入队。

代码

// luogu-judger-enable-o2
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<queue>

using namespace std;
const int MAXN = 200005;
typedef long long LL;

inline LL rd(){
	LL x=0,f=1;char ch=getchar();
	while(!isdigit(ch)) {f=ch=='-'?0:1;ch=getchar();}
	while(isdigit(ch))  {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
	return f?x:-x;
}

int n,cnt[MAXN];
LL s[MAXN],k[MAXN],f[MAXN],ans;
bool vis[MAXN];
queue<int> Q;
vector<int> son[MAXN],bl[MAXN];

inline void spfa(){
    for(int i=1;i<=n;i++) Q.push(i);
	while(Q.size()){
		int x=Q.front();Q.pop();LL sum=s[x];vis[x]=false;
		for(register int j=0;j<son[x].size();j++)
			sum+=f[son[x][j]];
		if(sum<f[x]) {
			f[x]=sum;
			for(register int j=0;j<bl[x].size();j++) 
			    if(!vis[bl[x][j]]) vis[bl[x][j]]=1,Q.push(bl[x][j]);
		}
	}
}

int main(){
	n=rd();int x;
	for(register int i=1;i<=n;i++){
		s[i]=rd(),k[i]=rd(),cnt[i]=rd();
		for(register int j=1;j<=cnt[i];j++) {x=rd();bl[x].push_back(i);son[i].push_back(x);}
		f[i]=k[i];vis[i]=1;
	}
	spfa();
	printf("%lld
",f[1]);
	return 0;
}

原文地址:https://www.cnblogs.com/sdfzsyq/p/9866786.html