1 条题解

  • 0
    @ 2026-9-30 12:43:55

    C++ :

    
    #include <cstdio>
    #include <algorithm>
    using namespace std;
    /* 从 1 出发,每次走「边权最小、并列取终点编号最小」的出边;
       走到已访问的点就停(该点不再输出)。N<=20000, M<=200000。 */
    struct E { int u, w, v; };
    static E e[200005];
    static int firstE[20005];
    static char vis[20005];
    bool cmp(const E &a, const E &b){
        if(a.u != b.u) return a.u < b.u;
        if(a.w != b.w) return a.w < b.w;
        return a.v < b.v;
    }
    int main(){
        int n, m;
        if(scanf("%d %d", &n, &m) != 2) return 0;
        for(int i = 0; i < m; i++) scanf("%d %d %d", &e[i].u, &e[i].v, &e[i].w);
        sort(e, e + m, cmp);
        for(int i = 1; i <= n; i++) firstE[i] = -1;
        for(int i = m - 1; i >= 0; i--) firstE[e[i].u] = i;    /* 取该点最小下标 */
        int cur = 1;
        vis[cur] = 1;
        printf("%d", cur);
        while(firstE[cur] >= 0){
            int nxt = e[firstE[cur]].v;
            if(vis[nxt]) break;
            vis[nxt] = 1;
            printf(" %d", nxt);
            cur = nxt;
        }
        putchar('\n');
        return 0;
    }
    
    
    • 1

    信息

    ID
    2681
    时间
    1000ms
    内存
    256MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者