Problem : [CQOI2009]中位数图
Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 0 Solved: 0
[ Submit][ Status]
Description
Input
Output
Sample Input
Sample Output
HINT
第三个样例解释:{4}, {7,2,4}, {5,7,2,4,3}和{5,7,2,4,3,1,6}
N<=100000
思路:要判断某数x在某区间中是中位数,那么把比x小的数都设为-1,把比x大的数都设成1,x设成零,就有前缀和sum[R] - sum[L-1] == 0,也就是sum[R] == sum[L-1]。
且n >= R >= pos ,1<= L <= pos。设数组cnt[i]记录前缀和为i出现了几次,因为i可能<0,所以要加上n,也就是cnt[i+n]。
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 100000 + 100;
int sum[maxn], cnt[maxn<<1];
int main() {
int n, x;
while (cin >> n >> x) {
memset(sum, 0, sizeof(sum));
memset(cnt, 0, sizeof(cnt));
int pos = -1;
for (int i = 1; i <= n; i ++) {
int temp; cin >> temp;
if (temp < x) temp = -1;
else if (temp > x) temp = 1;
else temp = 0, pos = i;
sum[i] = sum[i-1] + temp;
if (pos == -1) cnt[sum[i] + n] ++;
}
cnt[n] ++;
int res = 0;
// for (int i = 1; i <= n*2; i ++) cout << cnt[i] << ' ';
// cout << endl;
// for (int i = 1; i <= n*2; i ++) cout << sum[i] << ' ';
// cout << endl;
for (int i = pos; i <= n; i ++) {
res += cnt[sum[i] + n];
// cout << "sum[i]+n = " << sum[i] + n << " cnt[sum[i] + n] = " << cnt[sum[i] + n] << endl;
}
cout << res << '\n';
}
return 0;
}
2014




被折叠的 条评论
为什么被折叠?



