TLE 求调 玄关

UVA1599 Ideal Path

Hootime @ 2024-11-14 20:38:07

#include <bits/stdc++.h>
#define rint register int
using namespace std;
int n, m;
int to[200005], c[300005], nxt[200005], head[100005];
int dis[100005];
int q[200005], vis[200005], h, t;
int ans[200005], ansn;
void getdis();
void bfs();
int vn;
#define mkarc(u,v,col) (to[++vn]=v, c[vn]=col, nxt[vn]=head[u], head[u]=vn)
int main(){
    while(~scanf("%d %d", &n, &m)){
        for(rint i = 1; i <= n; i++) head[i] = 0, dis[i] = 0;
        vn = 0;
        for(rint i = 1; i <= m; ++i){
            int u, v, col;
            scanf("%d %d %d", &u, &v, &col);
            mkarc(u, v, col);
            mkarc(v, u, col);
        }
        getdis();
        bfs();
        printf("%d\n", ansn);
        for(int i = 1; i <= ansn; i++) printf("%d ", ans[i]);
        if(ansn) puts("");
    }

    return 0;
}
void getdis(){
    h = 0, t = 1;
    q[t] = n;
    for(rint i = 1; i <= n; ++i) vis[i] = false;
    vis[n] = true;
    while(h < t){
        int now = q[++h];
        for(rint i = head[now]; i; i = nxt[i]){
            if(vis[to[i]]) continue;
            vis[to[i]] = true;
            dis[to[i]] = dis[now]+1;
            q[++t] = to[i];
        }
    }

    return;
}
void bfs(){
    h = 0, t = 1, ansn = 0;
    q[t] = 1;
    for(rint i = 1; i <= n; ++i) vis[i] = false;
    vis[1] = true;
    while(h < t){
        rint minn = INT_MAX, tmp = h+1;
        for(; tmp <= t; ++tmp){
            for(rint i = head[q[tmp]]; i; i = nxt[i]){
                if(dis[q[tmp]] == dis[to[i]]+1) minn = min(minn, c[i]);
            }
        }
        if(minn == INT_MAX) return;
        ans[++ansn] = minn;
        tmp = t;
        for(++h; h <= tmp; ++h){
            for(rint i = head[q[h]]; i; i = nxt[i]){
                if(dis[q[h]] == dis[to[i]]+1 && c[i] == minn && !vis[to[i]]){
                    q[++t] = to[i];
                    vis[to[i]] = true;
                }
            }
        }
        --h;
    }

    return;
}
/*
4 6
1 2 1
1 3 2
3 4 3
2 3 1
2 4 4
3 1 1
7 8
1 2 1
1 3 1
2 4 1
3 4 1
4 5 1
5 7 1
4 7 2
6 7 1

*/

by Hootime @ 2024-11-14 20:41:10

样例过了,和题解以及 @lijunxi2026 对拍也没问题,玄 3 关求调


|