Powered by:NEFU AB-IN
Link
文章目录
- A1032 Sharing
- 题意
- 思路
- 代码
A1032 Sharing
-
题意
To store English words, one method is to use linked lists and store a word letter by letter. To save some space, we may let the words share the same sublist if they share the same suffix. For example, loading and being are stored as showed in
You are supposed to find the starting position of the common suffix (e.g. the position of i in Figure 1). -
思路
2012年408的42题
两种做法,这里介绍第一种做法,也是思维量比较大的一种- 第一种:
- 定义两个指针,分别指向各自头结点,往后遍历,如果有公共结点肯定是在后面重叠,且后面部分都是共同的
- 设不同部分为a和b,公共部分为c,则a + c + b = b + c + a,让两个指针一起走,a走到头就转向b,b走到头转向a,一定会在公共部分相遇,因为路程相同
- 如果没有公共部分,那么两个指针会都走完a,b全程,也就是最后都到-1
- 如图
- 第二种:
- 开哈希表,遍历a的所有结点,并打上标记,遍历b,如果碰到有标记的,就是第一个公共部分
ps:
- 如果id用string存的话,会慢很多很多,所以pat上,如果n很大的话,尽量还是scanf加上int读入id
- 如果scanf里int和char一块读入时,必须按照格式读入,否则char可能读到的是空格
- 第一种:
-
代码
/* * @Author: NEFU AB-IN * @Date: 2023-01-08 09:00:37 * @FilePath: \GPLT\A1032\A1032.cpp * @LastEditTime: 2023-01-08 09:18:30 */ #include <bits/stdc++.h> using namespace std; #define int long long #define SZ(X) ((int)(X).size()) #define IOS \ ios::sync_with_stdio(false); \ cin.tie(nullptr); \ cout.tie(nullptr) #define DEBUG(X) cout << #X << ": " << X << '\n' typedef pair<int, int> PII; const int N = 1e5 + 10, INF = 0x3f3f3f3f; int ne[N]; char w[N]; #undef int int heada, headb, n; signed main() { scanf("%d%d%d", &heada, &headb, &n); for (int i = 1; i <= n; ++i) { int addr, addr_ne; char ww; scanf("%d %c %d", &addr, &ww, &addr_ne); w[addr] = ww; ne[addr] = addr_ne; } auto p = heada, q = headb; while (p != q) { p = (p != -1 ? ne[p] : headb); q = (q != -1 ? ne[q] : heada); } if (~p) printf("%05d", p); else printf("-1"); return 0; }