码迷,mamicode.com
首页 > 其他好文 > 详细

PAT A1131 Subway Map

时间:2020-02-12 23:47:09      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:pac   pre   push   nsf   最优   nbsp   选择   sub   else   

dfs,选择最优路径并输出~

#include<bits/stdc++.h>
using namespace std;
const int maxn=10010;
unordered_map<int,int> line;
vector<int> g[maxn];
vector<int> path,tmp;
bool visit[maxn]={false};
int minCnt=1e9;
int minTransferCnt=1e9;
int st,ed;
int transfer (vector<int> v) {
    int cnt=0,preLine=0;
    for (int i=1;i<v.size();i++)
    if (line[v[i-1]*10000+v[i]]!=preLine) {
        cnt++;
        preLine=line[v[i-1]*10000+v[i]];
    }
    return cnt;
}
void dfs (int v) {
    visit[v]=true;
    tmp.push_back(v);
    if (v==ed) {
        int transferCnt=transfer(tmp);
        if (tmp.size()<minCnt) {
            minCnt=tmp.size();
            minTransferCnt=transferCnt;
            path=tmp;
        }
        else if (tmp.size()==minCnt&&transferCnt<minTransferCnt) {
            minTransferCnt=transferCnt;
            path=tmp;
        }
        visit[v]=false;
        tmp.pop_back();
        return;
    }
    for (int i=0;i<g[v].size();i++) {
        if (visit[g[v][i]]==false) {
            dfs (g[v][i]);
        }
    }
    visit[v]=false;
    tmp.pop_back();
}
int main () {
    int N;
    scanf ("%d",&N);
    int k,pre,x;
    for (int i=1;i<=N;i++) {
        scanf ("%d %d",&k,&pre);
        for (int j=1;j<k;j++) {
            scanf ("%d",&x);
            g[pre].push_back(x);
            g[x].push_back(pre);
            line[pre*10000+x]=line[x*10000+pre]=i;
            pre=x;
        }
    }
    int q;
    scanf ("%d",&q);
    for (int i=0;i<q;i++) {
        scanf ("%d %d",&st,&ed);
        fill (visit,visit+maxn,false);
        minTransferCnt=1e9;
        minCnt=1e9;
        tmp.clear();
        dfs (st);
        printf ("%d\n",path.size()-1);
        int preLine=line[path[0]*10000+path[1]];
        int pre=0;
        for (int j=0;j<path.size();j++) {
            if (line[path[j]*10000+path[j+1]]!=preLine) {
                printf ("Take Line#%d from %04d to %04d.\n",preLine,path[pre],path[j]);
                pre=j;
                preLine=line[path[j]*10000+path[j+1]];
            }
        }
    }
    return 0;
}

 

PAT A1131 Subway Map

标签:pac   pre   push   nsf   最优   nbsp   选择   sub   else   

原文地址:https://www.cnblogs.com/zhanglichen/p/12301517.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!