破碎的路径
Description
比爾去很多地方旅游過。他在旅游的同時留下了很多簡短的旅行筆記。筆記的形式是這樣的:
出發地 目的地
如下面就是三條合法的note:
SwimmingPool OldTree
BirdsNest Garage
Garage SwimmingPool
在某一次搬家的時候,比爾的筆記本不小心散架了。于是他的筆記的順序被完全打亂了。他想請你幫個忙,幫他把這些筆記的順序整理好,先寫的筆記在前面。幸運的是,同一個地方比爾至多只去過一次。也就是說,在這些筆記當中,一個地方至多出現兩次,一次作為目的地,一次作為出發地。
Input
第一行是一個整數n,表示筆記的條數。N <= 12000。接下來有n行,每行一條筆記。筆記的兩個單詞的長度都不會超過15,兩個單詞之間以一個空格分隔。
Output
輸出整理好順序的筆記.
Sample Input
3
SwimmingPool OldTree
BirdsNest Garage
Garage SwimmingPool
Sample Output
BirdsNest Garage
Garage SwimmingPool
SwimmingPool OldTree
Data Constraint
Hint
【限制】
對于50%的數據,n <= 1000。
對于100%的數據,n <= 12000。
分析
看題我們知道——這是一條鏈
我用了哈希,確定字符串的編號
如果在讀入中哈希表判斷已出現的,那么肯定同時作為出發地和目的地出現過,那么這個點很明顯就是中間的點
然后一遍遍歷一邊輸出即可
程序:
var u,v:array[0..12000]of longint; s1,s2:array[0..12000]of string; son:array[0..60000]of longint; hash:array[0..60000]of string; n,s:longint; b,p:array[0..60000]of boolean; zfc:string; function locate(s:string):longint; var l,h,k,i:longint; beginl:=length(s);h:=0;k:=1;for i:=0 to l-1 dobeginh:=h+(ord(s[i])*k) mod 56399;k:=k*10 mod 56399;end;while (hash[(h+i) mod 56399]<>'')and(hash[(h+i) mod 56399]<>s) do inc(i);exit((h+i) mod 56399); end;procedure insert(s:string); var i:longint; begini:=locate(s);hash[i]:=s; end;function member(s:string):boolean; var i:longint; begini:=locate(s);if hash[i]=s then exit(true) else exit(false); end;procedure init; var count,i:longint; beginreadln(n);count:=0;while (count<n) dobeginreadln(zfc);s1[count]:=copy(zfc,1,pos(' ',zfc)-1);s2[count]:=copy(zfc,pos(' ',zfc)+1,length(zfc)-pos(' ',zfc));if (member(s1[count])=true) then p[locate(s1[count])]:=true else insert(s1[count]);if (member(s2[count])=true) then p[locate(s2[count])]:=true else insert(s2[count]);inc(count);u[count]:=locate(s1[count-1]);v[count]:=locate(s2[count-1]);son[u[count]]:=count;end;for count:=0 to n-1 doif (p[locate(s1[count])]=false) then s:=locate(s1[count]); end;procedure print; var i:longint; begini:=son[s];while (i>0) dobeginwriteln(hash[u[i]],' ',hash[v[i]]);i:=son[v[i]];end; end;begininit;print; end.轉載于:https://www.cnblogs.com/YYC-0304/p/9500002.html
總結