【测试点三、四、五分析】1032 Sharing (25 分)_28行代码AC
立志用最少的代碼做最高效的表達
PAT甲級最優題解——>傳送門
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 Figure 1.
Figure 1
You are supposed to find the starting position of the common suffix (e.g. the position of i in Figure 1).
Input Specification:
Each input file contains one test case. For each case, the first line contains two addresses of nodes and a positive N (≤10^?5), where the two addresses are the addresses of the first nodes of the two words, and N is the total number of nodes. The address of a node is a 5-digit positive integer, and NULL is represented by ?1.
Then N lines follow, each describes a node in the format:
Address Data Next
whereAddress is the position of the node, Data is the letter contained by this node which is an English letter chosen from { a-z, A-Z }, and Next is the position of the next node.
Output Specification:
For each case, simply output the 5-digit starting position of the common suffix. If the two words have no common suffix, output -1 instead.
Sample Input 1:
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
Sample Output 1:
67890
Sample Input 2:
00001 00002 4
00001 a 10001
10001 s -1
00002 a 10002
10002 t -1
Sample Output 2:
-1
最初想猴戲來著,只遍歷next部分,如果出現兩次,就輸出,如果沒有,則輸出-1。但最后兩個樣例無法通過,查找題解后發現,樣例中也會出現很多無效節點。猴戲失敗。
正確解法:數組構建鏈表,不要擔心數組太大過不了,放心的開,大膽的開,往死里開。只要不開爆,一般來講都沒問題。
這里分享一下如何判斷數組是否被開爆。
1、全局變量定義的數組,一般可以開到1000萬
2、在int main()里定義的數組,大概可以開到50萬
3、計算方法:一個int變量為4字節,1024字節為1KB,那么,理論上開一個一千萬大小的int數組約耗費48MB內存,而PAT上多數題目的內存限制為64MB,因此,完全不用擔心數組開爆。當然,以上皆為理想狀態,一切以實際情況為準。
測試點三:共同節點出現在最后一位。
測試點四和測試點五:有很多無效的獨立節點,這些節點不會被算在兩條鏈表中。
//在while和do-while選擇上,要考慮好。 #include<bits/stdc++.h> using namespace std;const int maxn = 100000 + 10; //結果無需輸出value,因此無需定義value數組 , vis判斷地址出現次數 int List[maxn], vis[maxn]; int main() {ios::sync_with_stdio(false);int list1_f, list2_f, N; cin >> list1_f >> list2_f >> N;for(int i = 0; i < N; i++) {int address; char c; cin >> address >> c;cin >> List[address];} int next = list1_f, fin = -1;while(next != -1) {vis[next]++;next = List[next];} next = list2_f;while(next != -1) {vis[next]++;if(vis[next] > 1) { fin = next; goto loop; } //第一次出現 next = List[next];} loop:;if(fin == -1) cout << "-1\n";else cout << setw(5) << setfill('0') << fin << '\n'; return 0; }
耗時:
如果有更優質的解法可以在評論區留言。大家一起交流學習。
總結
以上是生活随笔為你收集整理的【测试点三、四、五分析】1032 Sharing (25 分)_28行代码AC的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【题意+推导讲解】1031 Hello
- 下一篇: 正式突破两千粉丝!开心!