#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll inf=1e15;
const int N=1e6+10;
struct date
{
int x,y,to;
ll t;
} p[N];
int n,m,k,d,x,y;
map<pair<int,int>,int>mp;
int main()
{
while(~scanf("%d%d%d",&n,&m,&k))
{
mp.clear();
int a1,b1,a2,b2,a,b,now=0;
ll c;
p[1].x=0;
p[1].y=0;
p[1].t=0;
p[1].to=2;
mp[make_pair(0,0)]=1;
d=1;
int t=1;
if(n==m)
{
t++;
p[t].x=n;
p[t].y=m;
p[t].t=n;
mp[make_pair(n,m)]=t;
}
else
{
while(1)
{
x=p[t].x;
y=p[t].y;
c=p[t].t;
//printf("%d %d %d %d\n",x,y,d,now);
if((x==0&&y==m)||(x==n&&y==0)||(x==n&&y==m)) break;
if(now==0)
{
if(d==1)
{
if(x+m<=n)
{
a=x+m;
b=m;
c+=m;
now=2;
d=-1;
}
else
{
a=n;
b=n-x;
c+=n-x;
now=1;
d=-1;
}
}
else
{
if(x-m>=0)
{
a=x-m;
b=m;
c+=m;
now=2;
d=1;
}
else
{
a=0;
b=x;
c+=x;
now=3;
d=1;
}
}
}
else if(now==1)
{
if(d==1)
{
if(y>=x)
{
a=0;
b=y-x;
c+=x;
now=3; //
d=-1;
}
else
{
a=x-y;
b=0;
c+=y;
now=0;
d=-1;
}
}
else
{
if(x+y<=m)
{
a=0;
b=x+y;
c+=x;
now=3;
d=1;
}
else
{
a=x-(m-y);
b=m;
c+=m-y;
now=2;
d=1;
}
}
}
else if(now==2)
{
if(d==1)
{
//printf("%d %d\n",x,y);
if(y>=x)
{
a=0;
b=y-x;
c+=x;
now=3;
d=-1;
}
else
{
a=x-y;
b=0;
c+=y;
now=0;
d=-1;
}
}
else
{
if(x+y<=n)
{
a=x+y;
b=0;
c+=y;
now=0;
d=1;
}
else
{
a=n;
b=y-(n-x);
c+=n-x;
now=1;
d=1;
}
}
}
else if(now==3)
{
if(d==1)
{
if(y+n<=m)
{
a=n;
b=y+n;
c+=n;
now=1;
d=-1;
}
else
{
a=m-y;
b=m;
c+=m-y;
now=2;
d=-1;
}
}
else
{
if(y<=n)
{
a=y;
b=0;
c+=y;
now=0;
d=1;
}
else
{
a=n;
b=y-n;//
c+=n;//
now=1;
d=1;
}
}
}
//printf("%d %d -> %d %d %d %d\n",p[t].x,p[t].y,a,b,d,now);
if(mp[make_pair(a,b)]!=0)
{
//printf("11\n");
break;
}
p[t+1].x=a;
p[t+1].y=b;
p[t+1].t=c;
p[t+1].to=p[t].to=t+1;
mp[make_pair(p[t+1].x,p[t+1].y)]=t+1;
t++;
}
}
//for(int i=1; i<=10; i++)
//printf("%d %d %d\n",p[i].x,p[i].y,p[i].t);
for(int i=0; i<k; i++)
{
scanf("%d%d",&x,&y);
ll ans=inf;
if(x<=y)
{
a1=0;
b1=y-x;
}
else
{
a1=x-y;
b1=0;
}
if(n-x>=m-y)
{
a2=x+m-y;
b2=m;
}
else
{
a2=n;
b2=y+n-x;
}
int t1=mp[make_pair(a1,b1)];
int t2=mp[make_pair(a2,b2)];
//printf("%d %d\n",t1,t2);
if(t1!=0&&t2!=0)
{
if(p[t1].to==t2)
{
ans=min(ans,p[t1].t+x-a1);
}
else
{
ans=min(ans,p[t2].t+a2-x);
}
}
if(x+y>=m)
{
a1=x+y-m;
b1=m;
}
else
{
a1=0;
b1=x+y;
}
if(x+y>=n)
{
a2=n;
b2=x+y-n;
}
else
{
a2=x+y;
b2=0;
}
t1=mp[make_pair(a1,b1)];
t2=mp[make_pair(a2,b2)];
//printf("%lld %d %d\n",ans,t1,t2);
if(t1!=0&&t2!=0)
{
if(p[t1].to==t2)
{
ans=min(ans,p[t1].t+x-a1);
}
else
{
ans=min(ans,p[t2].t+a2-x);
}
}
if(ans==inf) ans=-1;
printf("%lld\n",ans);
}
}
return 0;
}
Intel Code Challenge Final Round C. Ray Tracing【模拟】
最新推荐文章于 2017-05-29 15:42:52 发布