题目地址


易错点:

  • 重边的处理需要新建一个二维数组,仅当新边的长度比旧边的长度小时加边.

#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
const int MAXN=5010,MAXM=1000010,INF=2e9;
struct Edge{
    int from,to,w,nxt;
}e[MAXM];
int head[MAXN],edgeCnt=1;
void addEdge(int u,int v,int w){
    e[++edgeCnt].from=u;
    e[edgeCnt].to=v;
    e[edgeCnt].w=w;
    e[edgeCnt].nxt=head[u];
    head[u]=edgeCnt;
}
struct Node{
    int nowPoint,dis;
    bool operator <(Node another)const{
        return dis>another.dis;
    }
};
int s,dis[MAXN],cnt[MAXN];
void dijkstra(){
    priority_queue<Node> q;
    q.push(Node{s,0});
    dis[s]=0,cnt[s]=1;
    while(!q.empty()){
        Node nowNode=q.top();q.pop();
        int nowPoint=nowNode.nowPoint,nowDis=nowNode.dis;
        if(nowDis>dis[nowPoint])continue;
        for(int i=head[nowPoint];i;i=e[i].nxt){
            int nowV=e[i].to;
            if(nowDis+e[i].w<dis[nowV]){
                dis[nowV]=nowDis+e[i].w;
                q.push(Node{nowV,dis[nowV]});
                cnt[nowV]=cnt[nowPoint];
            }else if(nowDis+e[i].w==dis[nowV]){
                cnt[nowV]+=cnt[nowPoint];
            }
        }
    }
}
int cmp[MAXN][MAXN];
int main(){
    s=1;
    int n,m;
    scanf("%d%d",&n,&m);
    int t=n;
    for(int i=1;i<=n;i++)dis[i]=INF;
    for(int i=1;i<=m;i++){
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        if(cmp[u][v]==0||cmp[u][v]>w)
            addEdge(u,v,w),cmp[u][v]=w;
    }
    dijkstra();
    if(dis[t]==INF){
        printf("No answer\n");
        return 0;
    }
    printf("%d %d\n",dis[t],cnt[t]);
    return 0;
}