BZOJ 1975: [Sdoi2010]魔法猪学院【K短路,A*

就用dijkspfa这种玄学东西啊……

看题显然就是从最短路开始从小往大选择,于是就是求前k短路

考虑对于一个节点i,维护dis[i]表示从i到n的最短路长度,d1[i]表示从1到i当前走过的路径长度,用priority_queue维护这两个的和,每次取最小的显然最优

…………谁说priority_queue要卡空间啊……明明没卡嘛QAQ,辣鸡flaze xjb写了个配对堆MLE了一年233333


#include
#define MAXN 5005
#define MAXM 200005
using namespace std;	int n,m;double E;
const double eps = 1e-6;
struct t1{
	int to,nxt;
	double lth;
}edge[MAXM<<1];	int cnt_edge;
int fst[MAXN];
vector lik[MAXN];
vector lkk[MAXN];
inline void addedge(int x,int y,double l){
	edge[++cnt_edge].to = y;
	edge[cnt_edge].nxt = fst[x];
	edge[cnt_edge].lth = l;
	fst[x] = cnt_edge;
	
	lik[y].push_back(x);
	lkk[y].push_back(l);
}

double dis[MAXN];

int que[MAXN],head,tail;
int in_que[MAXN];
inline void SPFA(int now){
	for(int i=1;i<=n;++i)	dis[i] = 1e19;
	dis[now] = 0;
	head = tail = 0;
	que[tail++] = now;
	in_que[now] = 1;
	while(head^tail){
		now = que[head++];
		in_que[now] = 0;
		if(head==MAXN)	head = 0;
		for(int i=0;i+0u dis[now] + lkk[now][i]){
				dis[aim] = dis[now] + lkk[now][i];
				if(!in_que[aim]){
					que[tail++] = aim;
					in_que[aim] = 1;
					if(tail==MAXN)	tail = 0;
				}
			}
		}
	}
}

struct Node{
	double d1;
	int id;
	Node(){}
	Node(double d1,int id):d1(d1),id(id){}
	bool operator < (const Node & ano) const {
		return d1 > ano.d1;
	}
};

priority_queue pq;

inline void AStar(){
	int cnt = -1;
	pq.push(Node(dis[1],1));

	while((!pq.empty()) && E > -eps){
		Node KK = pq.top();
		pq.pop();

		int now = KK.id;	double dd = KK.d1 - dis[now];

		if(now==n){
			++cnt , E -= dd;
		}

		for(int tmp = fst[now];tmp;tmp=edge[tmp].nxt){
			int aim = edge[tmp].to;
			pq.push(Node(dd+edge[tmp].lth+dis[aim],aim));
		}
	}

	printf("%d",cnt);
}

int main(){
	freopen("1.in","r",stdin);
	freopen("orz.out","w",stdout);
	scanf("%d%d%lf",&n,&m,&E);

	for(int i=1;i<=m;++i){
		int x,y;
		double l;
		scanf("%d%d%lf",&x,&y,&l);
		addedge(x,y,l);
	}

	SPFA(n);
	//for(int i=1;i<=n;++i)	printf("dis[ %d ] = %f\n",i,dis[i]);
	AStar();
	
	return 0;
}


你可能感兴趣的:(OI,BZOJ,SPFA,A*)