PAT 1032 Sharing(哈希)

来源:互联网 发布:淘宝一分钱购物 编辑:程序博客网 时间:2024/06/06 03:04

题目

https://www.patest.cn/contests/pat-a-practise/1032

求两个链表的首个共同结点的地址。如果没有公共节点则输出-1。

解题思路

总体思想就是都地址哈希,由于不要求输出字符,所以不需要结构体。

刚开始想法是统计地址出现的次数,而不去遍历后来形成的链表,出现次数为3的地址即公共节点地址(也可能是首个地址则次数为2),但是尝试了很久都无法通过测试3和测试5,暂时没想出来为什么?难道是有多个公共节点?无解。

正确做法:遍历第一个链表,将所有出现的地址都标记为true,那么在遍历第二个链表时,遇到标记为true的节点就是两条链表的首个公共节点。

AC代码

#include <cstdio>#include <cstring>using namespace std;const int maxn = 100000;int node[maxn+5]; //node[i]记录地址为i的节点的后继节点地址bool inFirst[maxn]; //标记地址i是否出现在第一个链表里int main(){    memset(node, -1, sizeof(node));    memset(inFirst, false, sizeof(inFirst));    int s1, s2, n, from, to;    scanf("%d %d %d", &s1, &s2, &n);    char c;    for (int i = 0; i<n; ++i)    {        scanf("%d %c %d", &from, &c, &to);        node[from] = to; //后继节点位置    }    int tmp = s1;    while (tmp != -1)    {        inFirst[tmp] = true;        tmp = node[tmp];    }    tmp = s2;    while (tmp != -1)    {        if (inFirst[tmp] == true) //出现公共节点        {            printf("%05d\n", tmp); //输出五位数            return 0;        }        tmp = node[tmp];    }    printf("-1\n");    return 0;}
原创粉丝点击