1131 Subway Map(30分)

写的时候状态很差 最近没什么睡眠质量 可能写的有点啰嗦有点乱_(:з」∠)_对8⑦
又从柳神辣里偷技术回来了
无序map unordere_map超快
二元映射至一元的方案:hash
不是难题, DFS的最短路径问题

#include <cstdio>
#include <vector>
#include <queue>
#include <unordered_map>
#define INF 0x7FFFFFFF
using namespace std;
vector<vector<int>> G(10000);
unordered_map<int, int> line;
void BFS( int s, int d )
{
    vector<int> visited(10000), dist(10000, INF), path(10000, -1), trans(10000), ans;
    queue<int> q;
    int v, pre, l;
    q.push(s);
    visited[s] = 1;
    dist[s] = 0;
    while( !q.empty() )
    {
        v = q.front();
        q.pop();
        for( int i = 0; i < G[v].size(); ++i )
            if( dist[v] + 1 < dist[ G[v][i] ] )
            {
                path[ G[v][i] ] = v;
                dist[ G[v][i] ] = dist[v] + 1;
                trans[ G[v][i] ] = trans[v];
                if( path[v] != -1 && line[ path[v] * 10000 + v ] != line[ v * 10000 + G[v][i] ] )
                    ++trans[ G[v][i] ];
                if( !visited[ G[v][i] ] )
                {
                    visited[ G[v][i] ] = 1;
                    q.push( G[v][i] );
                }
            }
            else if( dist[v] + 1 == dist[ G[v][i] ] && trans[v] < trans[ G[v][i] ] )
            {
                path[ G[v][i] ] = v;
                dist[ G[v][i] ] = dist[v] + 1;
                trans[ G[v][i] ] = trans[v];
                if( path[v] != -1 && line[ path[v] * 10000 + v ] != line[ v * 10000 + G[v][i] ] )
                    ++trans[ G[v][i] ];
            }
    }
    for( int i = d; i != -1; i = path[i] )
        ans.push_back(i);
    pre = ans.back();
    l = line[pre * 10000 +  ans[ ans.size() - 2 ]];
    printf("%d\nTake Line#%d from %04d to ",ans.size() - 1, l, pre);
    for( int i = ans.size() - 2; i >= 0; --i )
    {
        if( l != line[pre * 10000 + ans[i]] )
        {
            l = line[pre * 10000 + ans[i]];
            printf("%04d.\nTake Line#%d from %04d to ", pre, l, pre);
        }
        pre = ans[i];
    }
    printf("%04d.\n", ans[0]);
}
int main()
{
    int N, K, cnt = 0;
    scanf("%d", &N);
    for( int i = 1, M, pre; i <= N; ++i )
    {
        scanf("%d %d", &M, &pre);
        for( int j = 1, station; j < M; ++j, pre = station )
        {
            scanf("%d", &station);
            if( j )
            {
                G[pre].push_back(station);
                G[station].push_back(pre);
                line[pre * 10000 + station] = line[station * 10000 + pre] = i;
            }
        }
    }
    scanf("%d", &K);
    for( int i = 0, s, d; i < K; ++i )
    {
        scanf("%d %d", &s, &d);
        BFS( s, d );
    }
}

发布了152 篇原创文章 · 获赞 144 · 访问量 9239

猜你喜欢

转载自blog.csdn.net/qq_43749739/article/details/100187783