7-13 航空公司VIP客戶查詢 (25 分)


題意:

 

 思路:

讀完題目之后的第一思路就是用map將客戶的id(string類型)與里程road(int類型)形成映射,然后直接用id查找添加里程或輸出里程。但是400ms的限制妥妥的超時了。然后意識到要用哈希做,但是用哈希就有一點不好解決,每個客戶的里程怎么保存,考慮了很長時間無果,搜了一下博客,發現可以用結構體來保存,平常用數組模擬鏈表的時候都是直接開的一維數組,所以當每個客戶的信息多了后就沒有結構體來的理解方便了。

第一次嘗試:這個題N的上限是1e5,所以將每個客戶的id轉換成long long類型,然后對1e5+7取余,結果作為下標對應到數組里邊存里程,完美過樣例,提交果斷WA。。。。。。。

第二次嘗試:又看了一遍題目,思考了一下,哈希會出現沖突,需要處理沖突。所以數組模擬鏈表處理沖突,提交AC。

代碼:

 1 #include <iostream>
 2 #include <queue>
 3 #include <cstdio>
 4 #include <algorithm>
 5 #include <cmath>
 6 #include <cstring>
 7 #include <queue>
 8 #include <map>
 9 #include <vector>
10 #define INF 0x3f3f3f3f
11 #define FRE() freopen("in.txt","r",stdin)
12 
13 using namespace std;
14 typedef long long ll;
15 typedef pair<int,string> P;
16 const int maxn = 1e5+7;
17 int head[maxn];
18 struct Peo{
19     char name[20];
20     int road;
21     int next;
22 }p[maxn];
23 int cnt = 0;
24 
25 int GetId(char* str) {
26     ll res = 0;
27     for(int i = 0; i<strlen(str); i++) {
28         if(isdigit(str[i])) {
29             res = res*10 + str[i]-'0';
30         } else {
31             res = res*10 + 10;
32         }
33     }
34     return (int)(res%maxn);
35 }
36 
37 void Add_Node(char* str,int id,int temp){
38     bool ok = true;
39     for(int i = head[id]; ~i; i = p[i].next){
40         if(strcmp(str,p[i].name) == 0){
41             p[i].road += temp;
42             ok = false;
43         }
44     }
45     if(ok){
46         int i = 0;
47         p[cnt].road += temp;
48         for(i = 0; str[i]; i++){
49             p[cnt].name[i] = str[i];
50         }
51         p[cnt].name[i] = '\0';
52         p[cnt].next = head[id];
53         head[id] = cnt++;
54     }
55     return;
56 }
57 
58 bool ToFind(char* str,int id){
59     for(int i = head[id]; i!=-1; i = p[i].next){
60         if(strcmp(str, p[i].name) == 0){
61             cout<<p[i].road<<endl;
62             return true;
63         }
64     }
65     return false;
66 }
67 
68 int main() {
69     char str[20];
70     int n,k,temp;
71     cin>>n>>k;
72     memset(head,-1,sizeof(head));
73     for(int i = 0; i<n; i++) {
74         cin>>str>>temp;
75         if(temp<k) temp = k;
76         int index = GetId(str);
77         Add_Node(str,index,temp);
78     }
79     int m;
80     cin>>m;
81     for(int i = 0; i<m; i++) {
82         cin>>str;
83         int index = GetId(str);
84         if(!ToFind(str,index)){
85             printf("No Info\n");
86         }
87     }
88     return 0;
89 }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM