南邮NOJ | NOJ2335 从N个数中找到最大的一个数字并输出
这两段代码可以解决问题,
但是会TIME ERROR
后来在世杰哥的帮助下
改变了思想
- 简单版
#include <iostream>
using namespace std;
int main()
{
long int i;
unsigned long long int *a = new unsigned long long int[1844674];
long int j = 0;
cin >> i;
for (j = 0; j < i; j++)
{
cin >> a[j];
}
unsigned long long int max = a[0];
for (j = 0; j < i; j++)
{
if (max < a[j])
{
max = a[j];
}
}
cout << max;
getchar();
getchar();
return 0;
}
2.更新版(分治法)
这个换了算法——分治法,
但是还是会超时。
#include <iostream>
using namespace std;
int main()
{
long int i;
unsigned long long int *a = new unsigned long long int[1844674];
long int j = 0;
cin >> i;
for (j = 0; j < i; j++)
{
cin >> a[j];
}
unsigned long long int max = a[0];
for (j = 0; j < i; j++)
{
if (max < a[j])
{
max = a[j];
}
}
cout << max;
getchar();
getchar();
return 0;
}
- 正确代码
简单来说,就是输入之后马上进行判断。
千万别堆了一大堆数字,再一个一个判断MAX,
可以,但没必要。
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<cstdio>
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
unsigned long long int positive_max = 0;
unsigned long long int negative_max = 9223372036854775808;
bool positive_flag = 0;
inline void read(){
unsigned long long int x = 0;
char c;
int t = 1;
while(!isdigit(c = getchar())){
if(c == '-'){
t = -1;
}
}
while(isdigit(c)){
x = x*10 + c - '0';
c = getchar();
}
if (t == 1) {
positive_flag = 1;
if (positive_max < x) {
positive_max = x;
}
}
else {
if (negative_max > x) {
negative_max = x;
}
}
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
read();
}
if (positive_flag) {
cout<<positive_max<<endl;
}
else {
cout<<"-"<<negative_max<<endl;
}
return 0;
}