1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| #include<iostream> #include<cstring> #include<queue> #include<string> #include<algorithm>
using namespace std; #define fi first #define se second typedef pair<int,int> PII;
const int N = 1e4+10,M=1e6+10; int post[N]; int h[N],ne[M],e[M],line[M],w[M],idx;
int dist[N],pre[N],cnt[N]; bool st[N]; string msg[N];
int n,k;
void add(int a,int b,int c,int id){ e[idx]=b;line[idx]=id;w[idx]=c;ne[idx]=h[a];h[a]=idx++; }
string get_num(int n){ string res=to_string(n); while(res.size()<4) res="0"+res; return res; }
void dijkstra(int S,int T){ memset(dist,0x3f,sizeof dist); memset(cnt,0x3f,sizeof cnt); memset(st,false,sizeof st); dist[S]=0;cnt[S]=0; priority_queue<PII,vector<PII>,greater<PII>> q; q.push({0,S}); while(q.size()){ auto p=q.top(); q.pop(); int t=p.se; if(st[t]) continue; st[t]=true; for(int i=h[t];~i;i=ne[i]){ int j=e[i]; if(dist[j]>dist[t]+w[i]){ dist[j]=dist[t]+w[i]; pre[j]=t; cnt[j]=cnt[t]+1; msg[j]="Take Line#"+to_string(line[i])+" from "+get_num(t)+" to "+get_num(j)+"."; q.push({dist[j],j}); }else if(dist[j]==dist[t]+w[i]){ if(cnt[j]>cnt[t]+1){ cnt[j]=cnt[t]+1; pre[j]=t; msg[j]="Take Line#"+to_string(line[i])+" from "+get_num(t)+" to "+get_num(j)+"."; } } } } vector<string> v; cout<<dist[T]<<endl; for(int i=T;i!=S;i=pre[i]) v.push_back(msg[i]); for(int i=v.size()-1;i>=0;i--) cout<<v[i]<<endl; }
int main(){ cin>>n; memset(h,-1,sizeof h); for(int i=1;i<=n;i++){ int m; cin>>m; for(int j=0;j<m;j++) cin>>post[j]; for(int j=0;j<m;j++){ for(int k=0;k<j;k++){ int len; if(post[0]!=post[m-1]) len=j-k; else len=min(j-k,m-1-j+k); add(post[j],post[k],len,i); add(post[k],post[j],len,i); } } } cin>>k; while(k--){ int S,T; cin>>S>>T; dijkstra(S,T); } return 0; }
|