您的位置:首页 > 其它

1032. Sharing (25)

2015-11-14 22:07 363 查看
1.直接建立两个100001长度的数组,一个用来当作链表使用,一个用来当作后面的哈希查询使用

2.遍历第一个链表,把第一个链表中存在的节点记录在哈希表中

3.遍历第二个链表,如果哈希中存在某个节点的值,就break,最终输出该节点值

4.把地址改为int存储,最后输出注意-1和其他的补0的情况

下面为AC代码:



//#include<string>
//#include <iomanip>
#include<vector>
#include <algorithm>
//#include<stack>
#include<set>
#include<queue>
#include<map>
//#include<unordered_set>
//#include<unordered_map>
//#include <sstream>
//#include "func.h"
//#include <list>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
using namespace std;

/*
11111 22222 9
67890 i 00002
00010 a 12345
00003 g -1
12345 D 67890
00002 n 00003
22222 B 23456
11111 L 00001
23456 e 67890
00001 o 00010

11111 22222 9
00012 i 00002
00010 a 12345
00003 g -1
12345 D 00012
00002 n 00003
22222 B 23456
11111 L 00001
23456 e 00012
00001 o 00010
*/
int main(void)
{
int *m = new int[100001];
int *exist = new int[100001];
memset(m, -1, sizeof(m));
memset(exist, -1, sizeof(exist));
int sum;
int a, b;
scanf("%d %d %d", &a, &b, &sum);
m[a] = -1;
m[b] = -1;

for (int i = 0; i < sum; i++)
{
char tmp[10];
int pre, next;
scanf("%d %s %d", &pre, tmp, &next);
m[pre] = next;
}
int head = a;
while (head != -1)
{//把第一个链表存进哈希表 exist中
exist[head] = 1;
head = m[head];
}
head = b;
while (head != -1)
{
if (exist[head] == 1)
{
break;
}
head = m[head];
}
if (head != -1)
printf("%05d\n", head);
else
printf("%d\n", head);

return 0;
}


下面使用map<string,string> 进行存储

最后一个例子超时



仅进行输入和结构存储:



源代码:

//#include<string>
//#include <iomanip>
#include<vector>
#include <algorithm>
//#include<stack>
#include<set>
#include<queue>
#include<map>
//#include<unordered_set>
#include<unordered_map>
//#include <sstream>
//#include "func.h"
//#include <list>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
using namespace std;

/*
11111 22222 9
67890 i 00002
00010 a 12345
00003 g -1
12345 D 67890
00002 n 00003
22222 B 23456
11111 L 00001
23456 e 67890
00001 o 00010

11111 22222 9
00012 i 00002
00010 a 12345
00003 g -1
12345 D 00012
00002 n 00003
22222 B 23456
11111 L 00001
23456 e 00012
00001 o 00010
*/
int main(void)
{

unordered_map<string, string> m;
unordered_map<string, string> exist;
int sum;
string a, b;
cin >> a >> b >> sum;
m[a] = "-1";
m[b] = "-1";
for (int i = 0; i < sum; i++)
{
char tmp[10];
char pre[10], next[10];
scanf("%s %s %s", &pre, tmp, &next);
string preStr = "";
string nextStr = "";
for (int i = 0; pre[i] != 0; i++)
preStr += pre[i];
for (int i = 0; next[i] != 0; i++)
nextStr += next[i];
m[preStr] = nextStr;
}
string head = a;
exist = m;
while (head != "-1")
{//把第一个链表存进哈希表 exist中
exist[head] = "A";
head = m[head];
}
head = b;
while (head != "-1")
{
if (exist[head] == "A")
{
break;
}
head = m[head];
}
cout << head << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: