1 Star 0 Fork 1

saigon/Algorithms

forked from charlieshu/Algorithms 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
P1346 电车.cpp 2.12 KB
一键复制 编辑 原始数据 按行查看 历史
charlie 提交于 2024-01-09 00:01 . move from github to gitee
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main(){
int n,start,stop,inf=0x7fffffff,tf=-1;
cin>>n>>start>>stop;
int fast[n];
start--;
stop--;
vector<int> v[n];
queue<int> q;
// cout<<n<<endl;
for(int i=0;i<n;i++){
fast[i]=inf;
int k;
cin>>k;
// cout<<" enter:"<<i<<" n:"<<n<<endl;
// v[i] = new vector<int>();
v[i].push_back(k+1);
for(int j=0;j<k;j++){
int l;
cin>>l;
v[i].push_back(l-1);
// if(n>=39) cout<<" enter:j:"<<j<<" k:"<<k<<" n:"<<n<<endl;
}
}
int little=start;
q.push(start);
fast[start]=0;
int len=0;
while(little != stop && !q.empty()){
little = q.front();
// cout<<"little:"<<little<<endl;
q.pop();
len = fast[little];
if(fast[v[little][1]]>len+0){
fast[v[little][1]] = len+0;
q.push(v[little][1]);
// cout<<" first find:"<<v[little][1]<<endl<<" len:"<<len<<endl<<endl;
n--;
if(q.front()==stop){
little = stop;
break;
}
}
int edge_len=v[little][0];
for(int i=1;i<edge_len;i++){
if(fast[v[little][i]]>len+1){
n--;
fast[v[little][i]] = len+1;
// cout<<" second find:"<<v[little][i]<<endl<<" len:"<<len+1<<endl<<endl;
if(v[little][i]==stop){
tf++;
if(tf){
little = stop;
break;
}
}
q.push(v[little][i]);
}
}
}
if(little==stop || fast[stop]!=inf){
cout<<fast[stop];
}
else{
cout<<-1;
}
return 0;
}
/*
test1, expect 0
================
3 2 1
2 2 3
2 3 1
2 1 2
test2, expect 1
================
4 2 3
3 4 2 3
2 4 3
2 1 4
2 2 3
test3, expect 0
================
4 1 4
3 4 2 3
2 4 3
2 1 4
2 2 3
test4, expect 0
================
4 1 4
3 4 2 3
2 4 3
3 1 4 3
4 2 3 4 4
test5, expect 1
================
4 3 4
4 1 4 2 3
2 4 3
3 1 4 3
4 2 3 4 4
test6, expect 1
================
4 3 2
1 3
2 1 3
2 1 2
2 1 3
test7, expect -1
================
4 3 2
1 3
2 1 3
2 1 4
2 1 3
*/
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/saigonshu/algorithm.git
git@gitee.com:saigonshu/algorithm.git
saigonshu
algorithm
Algorithms
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385