[usaco2009febgold]道路翻新 最短路+dp

这道题居然卡SPFA,难受,写了这么长时间的SPFA,都快把dij忘光了;

设d[i][j]为修j条路到i的最短距离,然后跑堆优化dij就行了;

实测中SPFA两组大数据超时严重;

dij约300ms一组大数据;

但是总感觉这个堆优化dij和SPFA好相像啊,奇怪;

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<ctime>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
#define LL long long
const int maxn=;
const int inf=;
struct node{
int x,y,next;
int v;
}e[maxn*];
int linkk[maxn],len=;
int n,m,k;
LL d[maxn][];
void insert(int x,int y,int v){
e[++len].y=y;
e[len].x=x;
e[len].next=linkk[x];
linkk[x]=len;
e[len].v=v;
}
void init(){
scanf("%d%d%d",&n,&m,&k);
int x,y,v;
for(int i=;i<=m;i++){
scanf("%d%d%d",&x,&y,&v);
insert(x,y,v);insert(y,x,v);
}
}
struct bian{
int x,k;
LL w;
bian(int a,int b,LL c){x=a,k=b,w=c;}
bool operator>(const bian& b)const{
return w>b.w;
}
};
priority_queue<bian,vector<bian>,greater<bian> > q;
void dij(){
memset(d,,sizeof(d));
for(int i=;i<=k;i++)d[][i]=;
q.push(bian(,,));
while(!q.empty()){
bian tmp=q.top();
q.pop();
int x=tmp.x;
int p=tmp.k;
LL w=tmp.w;
for(int i=linkk[x];i;i=e[i].next){
if(p<k&&w<d[e[i].y][p+]){
d[e[i].y][p+]=w;
q.push(bian(e[i].y,p+,w));
}
if(w+e[i].v<d[e[i].y][p]){
d[e[i].y][p]=w+e[i].v;
q.push(bian(e[i].y,p,d[e[i].y][p]));
}
}
}
}
void work(){
dij();
cout<<d[n][k]<<endl;
}
int main(){
init();
work();
}
上一篇:1--Python 入门--Python基础数据类型


下一篇:OC基础(12)