题目描述
比尔去很多地方旅游过。他在旅游的同时留下了很多简短的旅行笔记。笔记的形式是这样的:
出发地 目的地
如下面就是三条合法的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
对于100%的数据,n <= 12000。
分析
根据题目我们发现这题其实就是一条链!
然后很明显链上点用字符串编号不可能,于是我打了哈希,确定字符串的地址(你叫编号也行)
然后如何判断起点和终点呢?很简单,如果在读入中哈希表判断已出现的,那么肯定同时作为出发地和目的地出现过,那么这个点很明显就是中间的点
然后一遍遍历一边输出即可
#include <iostream>
#include <cstdio>
#include <string>
#define q 56399
using namespace std;
int n,son[q],u[12001],v[12001],s;
bool b[q],p[q];
string hash[q],s1[12001],s2[12001];;
int locate(string s)
{
int i=0,l=s.length(),h=0,k=1;
for (i=0;i<l;i++)
{
h=h+(s[i]*k)%q;
k=k*10%q;
}
while (hash[(h+i)%q]!=""&&hash[(h+i)%q]!=s)
i++;
return (h+i)%q;
}
void insert(string s)
{
int i=locate(s);
hash[i]=s;
}
bool member(string s)
{
int i=locate(s);
if (hash[i]==s)
return true;
else return false;
}
void init()
{
int count=0;
char c;
scanf("%d",&n);
scanf("%c",&c);
while (count<n)
{
cin>>s2[count];
scanf("%c",&c);
if (c==' ')
s1[count]=s2[count];
if (c=='\n')
{
if (member(s1[count])) p[locate(s1[count])]=1;
else insert(s1[count]);
if (member(s2[count])) p[locate(s2[count])]=1;
else insert(s2[count]);
count++;
u[count]=locate(s1[count-1]);v[count]=locate(s2[count-1]);
son[u[count]]=count;
}
}
for (count=0;count<n;count++)
if (p[locate(s1[count])]==0) s=locate(s1[count]);
}
void print()
{
int i;
i=son[s];
while (i>0)
{
cout<<hash[u[i]]<<' '<<hash[v[i]]<<endl;
i=son[v[i]];
}
}
int main()
{
init();
print();
}
本文介绍了一个基于哈希表和链式存储的算法,用于解决旅行笔记顺序混乱的问题。通过使用字符串哈希,确保每个地点唯一对应一个地址,并通过一次遍历来确定起点和终点,最终按正确顺序输出旅行笔记。
168万+

被折叠的 条评论
为什么被折叠?



