program NDK1332;
const
maxn=250000;
type
atp=record
x,y,time:longint;
end;
var
n,ans,st,ed:longint;
fx:char;
map:array [0..maxn] of atp;
procedure init;
var
i,x,y:longint;
ch:char;
begin
readln(n);
x:=0;
y:=0;
for i:=1 to n do
begin
read(ch);
case ch of
'N':dec(x);
'E':inc(y);
'W':dec(y);
'S':inc(x);
end;{case}
map[i].x:=x;
map[i].y:=y;
map[i].time:=i;
end;
end;
{qsort是先按照一个关键字排序,再按照另一个关键字排序。这样能表示一个关键字相等的情况下比较另一个关键字的大小}
procedure qsort1(l,r:longint);
var
i,j:longint;
m,t:atp;
begin
i:=l;
j:=r;
m:=map[(l+r) shr 1];
repeat
while (map[i].x<m.x) or ((map[i].x=m.x) and (map[i].y<m.y)) do inc(i);
while (map[j].x>m.x) or ((map[j].x=m.x) and (map[j].y>m.y)) do dec(j);
if i<=j then
begin
t:=map[i];
map[i]:=map[j];
map[j]:=t;
inc(i);
dec(j);
end;
until i>j;
if i<r then qsort1(i,r);
if l<j then qsort1(l,j);
end;
procedure qsort2(l,r:longint);
var
i,j:longint;
m,t:atp;
begin
i:=l;
j:=r;
m:=map[(l+r) shr 1];
repeat
while (map[i].y<m.y) or ((map[i].y=m.y) and (map[i].x<m.x)) do inc(i);
while (map[j].y>m.y) or ((map[j].y=m.y) and (map[j].x>m.x)) do dec(j);
if i<=j then
begin
t:=map[i];
map[i]:=map[j];
map[j]:=t;
inc(i);
dec(j);
end;
until i>j;
if i<r then qsort2(i,r);
if l<j then qsort2(l,j);
end;
procedure main;
var
i:longint;
begin
st:=maxlongint;
ed:=-maxlongint;
ans:=maxlongint;
qsort1(1,n);
for i:=1 to n do
begin
if (map[i].x=map[i-1].x) and (abs(map[i].time-map[i-1].time)<>1) then{处于一行或一列同时访问序不能相差1。}
begin
if abs(map[i].y-map[i-1].y)<=ans then
begin
if abs(map[i].y-map[i-1].y)=ans then{能进行更新的条件。}
begin
if map[i].time<=map[i-1].time then
begin
if (map[i].time<st) or ((map[i].time=st) and (map[i-1].time>ed)) then
begin
st:=map[i].time;
ed:=map[i-1].time;
fx:='W';
end;
end
else
begin
if (map[i-1].time<st) or ((map[i-1].time=st) and (map[i].time>ed)) then
begin
st:=map[i-1].time;
ed:=map[i].time;
fx:='E';
end;
end;
end
else
begin
if map[i].time<map[i-1].time then
begin
st:=map[i].time;
ed:=map[i-1].time;
fx:='W';
end
else
begin
st:=map[i-1].time;
ed:=map[i].time;
fx:='E';
end;
end;
ans:=abs(map[i].y-map[i-1].y);
end;
end;
end;
qsort2(1,n);
for i:=1 to n do
begin
if (map[i].y=map[i-1].y) and (abs(map[i].time-map[i-1].time)<>1) then
begin
if abs(map[i].x-map[i-1].x)<=ans then
begin
if abs(map[i].x-map[i-1].x)=ans then
begin
if map[i].time<=map[i-1].time then
begin
if (map[i].time<st) or ((map[i].time=st) and (map[i-1].time>ed)) then
begin
st:=map[i].time;
fx:='N';
end;
end
else
begin
if (map[i-1].time<st) or ((map[i-1].time=st) and (map[i].time>ed)) then
begin
st:=map[i-1].time;
ed:=map[i].time;
fx:='S';
end;
end;
end
else
begin
if map[i].time<map[i-1].time then
begin
st:=map[i].time;
ed:=map[i-1].time;
fx:='W';
end
else
begin
st:=map[i-1].time;
ed:=map[i].time;
fx:='E';
end;
end;
ans:=abs(map[i].x-map[i-1].x);
end;
end;
end;
end;
begin
assign(input,'NDK1332.in'); reset(input);
assign(output,'NDK1332.out'); rewrite(output);
init;
main;
writeln(ans,' ',st,' ',ed,' ',fx);
close(input); close(output);
end.
挑战(NDK1332)
最新推荐文章于 2024-07-21 13:14:23 发布