Three Lines (USACO 2012 US Open, Bronze Division Problem 2)
{ http://usaco.org/index.php?page=viewproblem2&cpid=131 USACO 2012 US Open, Bronze Division Problem 2. Three Lines by hcy 2012.10.23 } const m=50000; type arr=array[1..5,1..2] of longint; var n,i,j,max:longint; a:array[0..m,1..2] of longint; b:arr; function check(line,k:longint;c:arr):boolean; var i:integer; begin for i:=1 to line-1 do if ((c[i,1]=1) and (c[i,2]=a[k,1])) or ((c[i,1]=2) and (c[i,2]=a[k,2])) then exit(true); exit(false); end; function getk(line,k:longint;c:arr):longint; var i,j:longint; f:boolean; begin for j:=k to n do begin f:=false; for i:=1 to line-1 do if ((c[i,1]=1) and (c[i,2]=a[j,1])) or ((c[i,1]=2) and (c[i,2]=a[j,2])) then begin f:=true;break;end; if not f then exit(j); end; exit(n+1);//to the end end; procedure success; var i:longint; begin writeln(1); close(input);close(output); halt; end; procedure find(line,k:longint;c:arr); var i,s,t,nextk:longint; tc:arr; begin if (k>n) then if (line<=4) then success else exit; if line>4 then exit; if check(line,k,c) then begin nextk:=getk(line,k+1,c);// this is important.if u use find(line,k+1,c) then it may occur 'stack overflow error' for recursion too many times find(line,nextk,c) end else begin //x tc:=c; tc[line,1]:=1; tc[line,2]:=a[k,1]; find(line+1,k+1,tc); //y tc:=c; tc[line,1]:=2; tc[line,2]:=a[k,2]; find(line+1,k+1,tc); end; end; begin assign(input,'security.in');reset(input); assign(output,'security.out');rewrite(output); readln(n); for i:=1 to n do readln(a[i,1],a[i,2]); find(1,1,b); writeln(0); close(input);close(output); end.
or:
{ http://usaco.org/index.php?page=viewproblem2&cpid=131 USACO 2012 US Open, Bronze Division Problem 2. Three Lines by hcy 2012.10.23 } const m=50000; type arr=array[1..5,1..2] of longint; var n,i,j,max:longint; a:array[0..m,1..2] of longint; b:arr; function getk(line,k:longint;c:arr):longint;//find next position k which is not on the lines var i,j:longint; f:boolean; begin for j:=k to n do begin f:=false; for i:=1 to line-1 do if ((c[i,1]=1) and (c[i,2]=a[j,1])) or ((c[i,1]=2) and (c[i,2]=a[j,2])) then begin f:=true;break;end; if not f then exit(j); end; exit(n+1);//to the end end; procedure success; var i:longint; begin writeln(1); close(input);close(output); halt; end; procedure find(line,k:longint;c:arr); var i,s,t,nextk:longint; tc:arr; begin if (k>n) then if (line<=4) then success else exit; if line>4 then exit; begin //x tc:=c; tc[line,1]:=1; tc[line,2]:=a[k,1]; nextk:=getk(line+1,k+1,tc);// this is important.if u use find(line,k+1,c) then it may occur 'stack overflow error' for recursion too many times find(line+1,nextk,tc); //y tc:=c; tc[line,1]:=2; tc[line,2]:=a[k,2]; nextk:=getk(line+1,k+1,tc); find(line+1,nextk,tc); end; end; begin assign(input,'security.in');reset(input); assign(output,'security.out');rewrite(output); readln(n); for i:=1 to n do readln(a[i,1],a[i,2]); find(1,1,b); writeln(0); close(input);close(output); end.
tip:
递归写起来很简单,但一定记得尽量减少递归次数!否则堆栈溢出!