pat1032 Sharing

题意:两个链表,找到公共后缀的第一个位置。

思路:遍历,计数即可。

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>

using namespace std;

map<int, int> nxt;
map<int, int> cnt;
char a[10];
int n;
int b1, b2;
int s, e;
int ans;

int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    scanf("%d %d %d", &b1, &b2, &n);
    ans = -1;
    for (int i = 0; i < n; i++) {
        scanf("%d %s %d", &s, a, &e);
        nxt[s] = e;
    }
    while (b1 != -1) {
        cnt[b1]++;
        b1 = nxt[b1];
    }
    while (b2 != -1) {
        cnt[b2]++;
        if (cnt[b2] == 2) {
            ans = b2; break;
        }
        b2 = nxt[b2];
    }
    if (ans == -1) printf("-1\n");
    else printf("%05d\n", ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/csx0987/article/details/82077490