题目链接:http://poj.org/problem?id=1724
思路:
有限制的最短路,或者说是二维状态吧,在求最短路的时候记录一下花费即可。一开始用SPFA写的,900MS险过啊,然后改成Dijkstra+priority_queue,60MS,orz.
SPFA:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
#define MAXN 104
#define inf 1<<30
typedef pair<int,int>Pair; struct Edge{
int v,w,c;
Edge(int vv,int ww,int cc):v(vv),w(ww),c(cc){}
}; vector<vector<Edge> >map;
int dist[MAXN][MAXN*MAXN];//在点i花费j的最短路径
bool mark[MAXN][MAXN*MAXN];
int k,n,m,MIN; bool SPFA()
{
memset(mark,false,sizeof(mark));
for(int i=;i<=n;i++)
for(int j=;j<=k+;j++)
dist[i][j]=inf;
queue<Pair>Q;
Q.push(make_pair(,));
dist[][]=;
mark[][]=true;
while(!Q.empty()){
Pair pp=Q.front();
Q.pop();
int u=pp.first,c=pp.second;
mark[u][c]=false;
for(int i=;i<map[u].size();i++){
int v=map[u][i].v;
int w=map[u][i].w;
int cc=map[u][i].c+c;
if(cc>k)continue;
if(dist[u][c]+w<dist[v][cc]){
dist[v][cc]=dist[u][c]+w;
if(!mark[v][cc]){
mark[v][cc]=true;
Q.push(make_pair(v,cc));
}
}
}
}
MIN=inf;
for(int i=;i<=k;i++)MIN=min(MIN,dist[n][i]);
return MIN<inf;
} int main()
{
int u,v,w,c;
while(~scanf("%d%d%d",&k,&n,&m)){
map.clear();map.resize(n+);
while(m--){
scanf("%d%d%d%d",&u,&v,&w,&c);
map[u].push_back(Edge(v,w,c));
}
if(SPFA()){
printf("%d\n",MIN);
}else
puts("-1");
}
return ;
}
Dijkstra+priority_queue:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
#define MAXN 104
#define inf 1<<30
typedef pair<int,int>Pair; struct Edge{
int v,w,c;
Edge(int vv,int ww,int cc):v(vv),w(ww),c(cc){}
}; struct Node{
int u,dd,cost;
bool operator < (const Node &p) const {
if(p.dd==dd)return p.cost<cost;
return p.dd<dd;
}
}; vector<vector<Edge> >map;
int k,n,m,MIN; bool Dijkstra()
{
priority_queue<Node>Q;
Node p,q;
p.u=,p.dd=,p.cost=,MIN=inf;
Q.push(p);
while(!Q.empty()){
p=Q.top();
Q.pop();
int u=p.u,dd=p.dd,cost=p.cost;
if(u==n){ MIN=dd;break; }
for(int i=;i<map[u].size();i++){
int v=map[u][i].v,w=map[u][i].w,c=map[u][i].c;
if(cost+c<=k){
q.u=v;q.dd=dd+w;q.cost=cost+c;
Q.push(q);
}
}
}
return MIN<inf;
} int main()
{
int u,v,w,c;
while(~scanf("%d%d%d",&k,&n,&m)){
map.clear();map.resize(n+);
while(m--){
scanf("%d%d%d%d",&u,&v,&w,&c);
map[u].push_back(Edge(v,w,c));
}
if(Dijkstra()){
printf("%d\n",MIN);
}else
puts("-1");
}
return ;
}