【1032 25 链表】 Sharing

传送门

题意

给定两个链表的起始地址 \(l,r\),两个链表中所有的总共节点个数 \(n\),问两个人链表有没有公共后缀

数据范围

\(n\leq 10^{5}\)

题解

  • 模拟链表,建地址值域的数组表示地址,值表示 next 指针
  • 先将第一个链表从头访问将访问到的地址标记,第二个访问到的第一个带标记的即所求

Code

#include <bits/stdc++.h>
using namespace std;

const int N = 1e6;

vector<int> lst(N);
vector<bool> st(N, false);
int main() {
	int a, b; cin >> a >> b;
	int n; cin >> n;
	for (int i = 0; i < n; i++) {
		char c;
		int add, nxt; cin >> add >> c >> nxt;
		lst[add] = nxt;
	}
	int ans = -1;
	while (a != -1) {
		st[a] = 1;
		a = lst[a];
	}
	while (b != -1) {
		if (st[b]) {
			ans = b;
			break;
		}
		b = lst[b];
	}
	if (ans == -1) cout << ans;
	else cout << setfill('0') << setw(5) << ans;
}

posted @ 2021-02-18 23:54  Hyx'  阅读(61)  评论(0)    收藏  举报