算法思想
读入数组A的n个数时,插入set,记录每个Ai存储的位置,同一个值存储的所有位置记录在一个向量中。统计数组A的非零段个数,作为参考值。
P依次从set中取值(从小到大)(如果值为0,跳过),依据位置向量获得每个值在数组A中的位置。
该位置的值赋值为0
如果该位置的前后的值都大于0,则非零段数加1如果该位置的前后的值都等于0,则非零段数减1更新非零段的最大值。
代码
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int A[500002];
vector<int> pos[10001];//数组
int main() {
int n;
cin >> n;
set<int> s;//集合
int num = 0;
A[0] = 0;
for (int i=1; i<=n; i++) {
cin >> A[i];
s.insert(A[i]);
pos[A[i]].push_back(i);
if (A[i-1]==0 && A[i]!=0)
num++;
}
A[n+1] = 0;
int maxx, temp;
maxx = temp = num;
set<int>::iterator it = s.begin();
if (*it == 0)
it++;
while (it != s.end()) {
vector<int> cp = pos[*it];
for (int i=0; i<cp.size(); i++) {
int id = cp[i];
A[id] = 0;
if (A[id-1]!=0 && A[id+1]!=0)
temp++;
if (A[id-1]==0 && A[id+1]==0)
temp--;
}
it++;
maxx = max(maxx, temp);
}
cout << maxx << endl;
return 0;
}
总结
如果使用暴力方式只能得到70分,因为时间消耗太多,所以必须进行优化
C++STL是一个高效的工具,包括vector,set,string,list等。