有条件的最短路

题目:https://ac.nowcoder.com/acm/contest/884/J

题意:n个点m条有权边,求s到t的最小费用,可以让你免费通行最多k条边

思路:分层最短路模板题,跑dijkstra,用dis[i][j]表示到i点且已经免费通行了j条边的最小花费

#include<bits/stdc++.h>
using namespace std;
#define N 1010
#define inf 0x3f3f3f3f
struct edge{int v,w,next;}e[2*N];
struct node
{
    int u,d,kk;
    bool operator <(const node&a)const
    {
        return d>a.d;
    }
};
int head[N],tot,n,m,s,t,k;
int dis[N][N],vis[N][N];
void add(int x,int y,int z)
{
    e[++tot].v=y;
    e[tot].w=z;
    e[tot].next=head[x];
    head[x]=tot;
}
void dijkstra()
{
    memset(dis,inf,sizeof(dis));
    dis[s][0]=0;
    priority_queue<node>q;
    q.push((node){s,0,0});
    while(!q.empty())
    {
        node t=q.top();q.pop();
        int u=t.u,nowk=t.kk;
        if(vis[u][nowk])continue;
        vis[u][nowk]=1;
        for(int i=head[u];i;i=e[i].next)
        {
            int v=e[i].v,w=e[i].w;
            if(nowk<k&&dis[v][nowk+1]>dis[u][nowk])//免费通行
            {
                dis[v][nowk+1]=dis[u][nowk];
                q.push(node{v,dis[v][nowk+1],nowk+1});
            }
            if(dis[v][nowk]>dis[u][nowk]+w)//不能免费通行
            {
                dis[v][nowk]=dis[u][nowk]+w;
                q.push(node{v,dis[v][nowk],nowk});
            }
        }
    }
}
int main()
{
    cin>>n>>m>>s>>t>>k;
    int a,b,c;
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&a,&b,&c);
        add(a,b,c);
        add(b,a,c);
    }
    dijkstra();
    int ans=inf;
    for(int i=0;i<=k;i++)
        ans=min(ans,dis[t][i]);
    cout<<ans<<endl;
    return 0;
}

**题目**:NCNA 2018 Tima goes to Xentopia **题意**:n个点m条有权边,每条边有红、蓝、白三种颜色,求s到t刚好经过k1条红边,k2条蓝边的花费的最短时间,边可以经过多次 **思路**:跑dijkstra,dis[i][j][k]表示到i点且经过j条红边和k条蓝边的最小花费,用来记录结果 ``` #include using namespace std; typedef long long LL; const int maxx = 455; struct edge { int v,ne,co; LL w; }e[2500]; struct node { int to,re,bl; LL cost; bool operator < (const node &t)const { return cost>t.cost; } }; LL dis[maxx][801][110]; int head[maxx],tot=-1; int k1,k2; void add(int u,int v,LL w,int co) { e[++tot].v=v;e[tot].w=w;e[tot].co=co; e[tot].ne=head[u];head[u]=tot; } void dijkstra(int s) { memset(dis,-1,sizeof(dis)); priority_queueq; q.push(node{s,0,0,0}); while(!q.empty()) { node now=q.top(); q.pop(); int u=now.to,re=now.re,bl=now.bl; LL cost=now.cost; if(dis[u][re][bl]!=-1)continue; dis[u][re][bl]=cost; for(int i=head[u];i!=-1;i=e[i].ne) { if(e[i].co==1) { node t=node{e[i].v,re+1,bl,cost+e[i].w}; if(t.re<=k1&&dis[t.to][t.re][t.bl]==-1)q.push(t); } else if(e[i].co==2) { node t=node{e[i].v,re,bl+1,cost+e[i].w}; if(t.bl<=k2&&dis[t.to][t.re][t.bl]==-1)q.push(t); } else { node t=node{e[i].v,re,bl,cost+e[i].w}; if(dis[t.to][t.re][t.bl]==-1)q.push(t); } } } } int main() { memset(head,-1,sizeof(head)); int n,m; cin>>n>>m>>k1>>k2; int flag=0; if(k1>s>>t; dijkstra(s); printf("%lld\n",dis[t][k1][k2]); return 0; } ```
posted @ 2019-10-06 19:39  灰灰烟影  阅读(212)  评论(0编辑  收藏  举报