跳到正文

题解

题解:P3843 [TJOI2007] 迷路

kongzixiao约 4 分钟
原文
文章信息与版本

文章信息

发布
2024年8月21日
收录
2025年12月12日
更新
2026年11月4日
篇幅
约 4 分钟
题目
P3843

版本

  1. v1当前

典型错误

乍一看,此题不就是一道非常水的模拟题吗?

C++
#include<bits/stdc++.h>
using namespace std;
int sx1,sx2,sy1,sy2,n,m,d1[1005],d2[1005];
char c1[1005],c2[1005];
double ans;
int main(){
	cin>>sx1>>sy1>>n;
	for(int i=1;i<=n;i++)cin>>d1[i]>>c1[i];
	cin>>sx2>>sy2>>m;
	for(int i=1;i<=m;i++)cin>>d2[i]>>c2[i];
	ans=sqrt((sx1-sx2)*(sx1-sx2)*1.00+(sy1-sy2)*(sy1-sy2)*1.00);
	for(int i=1;i<=n*m;i++){
		if(c1[(i-1)%n+1]=='X')sx1+=d1[(i-1)%n+1];
		else sy1+=d1[(i-1)%n+1];
		if(c2[(i-1)%m+1]=='X')sx2+=d2[(i-1)%m+1];
		else sy2+=d2[(i-1)%m+1];
		ans=sqrt((sx1-sx2)*(sx1-sx2)*1.00+(sy1-sy2)*(sy1-sy2)*1.00);
	}
	printf("%0.2lf",ans);
	return 0;
}

可是,这样只有14分!!!

为什么呢?

因为我们看错了题,这个dd是每个任务总共要走的路程,但是两个人每秒只能走一个单位!

正确思路

我们统计两人在一个周期内要走的时间t1t1和t2t2,然后求解其最小公倍数tt。

在11到tt范围内,一步一步执行操作即可。

于是有了以下代码:

AC代码

C++
#include<bits/stdc++.h>
using namespace std;
int sx1,sx2,sy1,sy2,n,m,t1,t2,d1[105],d2[105];
char c1[105],c2[105];
double ans=1e9;
int main(){
	cin>>sx1>>sy1>>n;
	for(int i=1;i<=n;i++)cin>>d1[i]>>c1[i],t1+=abs(d1[i]);
	cin>>sx2>>sy2>>m;
	for(int i=1;i<=m;i++)cin>>d2[i]>>c2[i],t2+=abs(d2[i]);
	//读入 
	int t=t1*t2/__gcd(t1,t2);
	//求需要枚举的时间 
	int nowc1=1,nowc2=1,nowd1=1,nowd2=1,tot1=1,tot2=1;
	//初始化几个变量
	for(int i=1;i<=t;i++){
		if(nowd1>abs(d1[tot1]))nowd1=1,nowc1++,tot1++;
		if(nowd2>abs(d2[tot2]))nowd2=1,nowc2++,tot2++;
		//如果执行完了这次操作,更新以下 
		if(tot1>n)tot1=1,nowd1=1,nowc1=1;
		if(tot2>m)tot2=1,nowd2=1,nowc2=1;
		//完成一个周期后更新 
		int flag1,flag2;
		if(d1[tot1]>0)flag1=1;
		else flag1=-1;
		if(d2[tot2]>0)flag2=1;
		else flag2=-1;
		if(c1[nowc1]=='X')sx1+=flag1;
		else sy1+=flag1;
		if(c2[nowc2]=='X')sx2+=flag2;
		else sy2+=flag2;
		nowd1++,nowd2++;
		//执行操作 
		ans=min(ans,sqrt((sx1-sx2)*(sx1-sx2)*1.00+(sy1-sy2)*(sy1-sy2)*1.00));
		//求最短距离 
	}
	printf("%0.2lf",ans); 
	return 0;
}

思路很简单,但是必须细心仔细哦~~~

原文