HDU 1029 Ignatius and the Princess IV (数据结构)

http://acm.hdu.edu.cn/showproblem.php?pid=1029

这道题最容易想到的写法就是用一个数组来记录每个数字出现的次数。但是,如果数的范围大的话就不太友好了,容易超时。

然后一开始做的时候也是很纠结。然后就了解到了这个写法~ 真的很厉害!(题解思路来自灯神~)

这里给出的是n个数字,而且n是奇数。这里不用太纠结。。。反正最多的那个数最后一定能留下来。不用排序。

先初始化一个栈。

读取整数的时候判断:1、栈是否为空。  2、栈顶元素是否等于当前读入的元素 - > (1)相等 (2)不相等

若栈为空,则将当前的数字放进栈内。

若相等,则进栈。否则出栈。

最后输出栈顶元素就行啦~

代码:

 1 #include <cmath>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <climits>
 6 #include <map>
 7 #include <set>
 8 #include <queue>
 9 #include <stack>
10 #include <vector>
11 #include <string>
12 #include <iostream>
13 #include <algorithm>
14 
15 
16 #define N 100010
17 
18 using namespace std;
19 
20 typedef long long int ll;
21 
22 stack<int> a;
23 int main()
24 {
25     int n;
26     while(cin>>n){
27         int num;
28         for(int i=0; i<n; i++){
29             cin>>num;
30             if(a.empty()){
31                 a.push(num);
32             }
33             else if(a.top()==num){
34                 a.push(num);
35             }
36             else{
37                 a.pop();
38             }
39         }
40         cout<<a.top()<<'\n';
41         while(!a.empty()) a.pop();
42     }
43     return 0;
44 }

最后不要忘了清空栈,因为是多实例~

更加优化的写法 (空间复杂度O ( 1 ) ) :

不设置栈,而是用一个变量来储存我们需要的那个值。

然后设置一个计数器,判断栈是否为空。

 1 #include <bits/stdc++.h>
 2 
 3 #define N 100010
 4 
 5 using namespace std;
 6 
 7 typedef long long int ll;
 8 
 9 //stack<int> a;
10 int main()
11 {
12     int n;
13     while(cin>>n){
14         int num, cnt, cnd;
15         cnt=0;
16         for(int i=0; i<n; i++){
17             cin>>num;
18             if(cnt==0){
19                 cnd=num;
20                 cnt++;
21             }
22             else if(cnd==num){
23                 cnt++;
24             }
25             else cnt--;
26         }
27         cout<<cnd<<endl;
28     }
29     return 0;
30 }

猜你喜欢

转载自www.cnblogs.com/Arrokoth/p/12185173.html