题解:P13415 [COCI 2012/2013 #4] VOYAGER
xa2024086
·
·
题解
一、题目介绍。
题目链接
我们要模拟信号的传播路径,信号会在网格中传播,碰到边缘或黑洞就消失,碰到行星就反弹。我们的目标是选出可以传播最长时间的方向,如果可以一直传下去,就输出 Voyager。
二、做法。
首先信号沿着当前方向碰到边缘、行星、黑洞时的判断(这个只要写几个 if 语句就行了)
X:判断是好写,可是怎么判断是否可以一直传下去呢?
Y:这个可以先定义一个 vis 数组,用来存放这个点有没有已经走过了这个方向,如果走过,就说明已经进入循环了。
Y同学说的没错,可以定义一个 vis 数组,
```
Y:但是有了判断循环方法,但是怎么储存呢?
X:可以用一个 bool 类型变量记录一下,每一次在退出时判断一下,如果是循环,就将记录传播时间的变量修改为 inf 。
```
是的,虽然说不修改记录传播时间的变量,最后也可以过。
[测评记录](https://www.luogu.com.cn/record/242070114)
但是要是数据强一点,就可以卡到你,所以在这里我的方法是修改。
## 三、[AC代码讲解。](https://www.luogu.com.cn/record/242278701)
```cpp
#include <bits/stdc++.h> //万能头
using namespace std;
#define int long long //一句俗话说得好,不开longlong见祖宗
int n,m; //这里是定义
char a[600][600];
int pr,pc;
bool vis[600][600][5];
int ulen,rlen,dlen,llen; //ulen代表向上发射的最长传播路线……(其他一样)
bool sq=0; //sq表示当前路线可不可以陷入循环
int ans; //登记最后答案
int dfs(int x,int y,int r){ //x和y是坐标,r是方向
if(x<1||x>n||y<1||y>m||sq||a[x][y]=='C'){ //这里是判断越界和黑洞,(如果sq为1,后面就不用继续了,可以加快速度)
return 0;
}
if(a[x][y]=='\\'){ //由于“\“不能直接输入,会报错,所以用要双写。
if(r==1){
r=4;
}
else if(r==2){
r=3;
}
else if(r==3){
r=2;
}
else{
r=1;
}
}
//小行星1
if(a[x][y]=='/'){
if(r==1){
r=2;
}
else if(r==2){
r=1;
}
else if(r==3){
r=4;
}
else{
r=3;
}
}
//小行星2
if(vis[x][y][r]){
sq=1;
return 0;
}
//如果为1就是说已经进入循环,有疑问的话前面有介绍
vis[x][y][r]=1;
if(r==1){
return (dfs(x-1,y,r)+1);
}
else if(r==2){
return (dfs(x,y+1,r)+1);
}
else if(r==3){
return (dfs(x+1,y,r)+1);
}
else{
return (dfs(x,y-1,r)+1);
}
//改变方向并继续DFS
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0); //好习惯
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
cin>>pr>>pc; //输入
for(int q=1;q<=4;q++){
sq=0;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
for(int k=1;k<=4;k++){
vis[i][j][k]=0;
}
}
} //清空,如果还没理解sq是什么意思,请继续向下看
//这里是开始模拟并存储
if(q==1){
ulen=dfs(pr,pc,q);
if(sq){
ulen=INT_MAX;
} //如果可以进入循环,更改为INF
}
else if(q==2){
rlen=dfs(pr,pc,q);
if(sq){
rlen=INT_MAX;
}
}
else if(q==3){
dlen=dfs(pr,pc,q);
if(sq){
dlen=INT_MAX;
}
}
else if(q==4){
llen=dfs(pr,pc,q);
if(sq){
llen=INT_MAX;
}
}
}
ans=max(max(ulen,rlen),max(dlen,llen));
//这里是输出
if(ans==ulen){
cout<<"U"<<endl;
}
else if(ans==rlen){
cout<<"R"<<endl;
}
else if(ans==dlen){
cout<<"D"<<endl;
}
else if(ans==llen){
cout<<"L"<<endl;
}
//由于有循环就将储存变量变为INF,所以如果ans=INF,那么意味着有可以循环的发射方向,所以输出“Voyager”
if(ans==INT_MAX){
cout<<"Voyager"<<endl;
}
else{
cout<<ans<<endl;
}
return 0; //完美收场
}
```