51nod-1682 中位数计数
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                51nod-1682 中位数计数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                原題鏈接
1682?中位數計數 基準時間限制:1?秒 空間限制:131072?KB 分值:?40?難度:4級算法題 ?收藏 ?關注
中位數定義為所有值從小到大排序后排在正中間的那個數,如果值有偶數個,通常取最中間的兩個數值的平均數作為中位數。
現在有n個數,每個數都是獨一無二的,求出每個數在多少個包含其的區間中是中位數。
Input 第一行一個數n(n<=8000) 第二行n個數,0<=每個數<=10^9 Output N個數,依次表示第i個數在多少包含其的區間中是中位數。 Input示例 5 1?2?3?4?5 Output示例 1?2?3?2?1
把輸入的數存在num數組中,對于num數組的每個元素num[i], 設maxs 為大于num[j]的元素個數,mins為小于num[j]元素個數,遍歷j = i-1 to 0, 若num[j] > num[i], maxs++, else mins++, d[8000+maxs - mins]++;遍歷完后ans += d[8000]表示0到i中滿足條件的區間,maxs = 0, mins = 0, 再遍歷i+1到n-1, 若num[j] > num[i] maxs++, else mins++, ans += d[8000+mins-maxs]
ans為num[i]滿足條件的區間個數
#include <cstdio> #include <cstring> #define maxn 8005 #define MOD 1000000007 using namespace std; typedef long long ll;int num[maxn], p[maxn<<1]; int kk[maxn]; int main(){// freopen("in.txt", "r", stdin);int n;scanf("%d", &n);for(int i = 0; i < n; i++)scanf("%d", num+i);int e = 0;for(int i = 0; i < n; i++){memset(p, 0, sizeof(p));p[8000] = 1;int cnt = 0, ans = 0;for(int j = i-1; j >= 0; j--){if(num[j] > num[i])cnt++;elsecnt--;p[cnt+8000]++;}ans += p[8000];cnt = 0;for(int j = i+1; j < n; j++){if(num[j] > num[i])cnt++;elsecnt--;ans += p[-cnt+8000];}kk[e++] = ans;}for(int i = 0; i < e; i++){if(i)putchar(' ');printf("%d", kk[i]);}puts("");return 0; }總結
以上是生活随笔為你收集整理的51nod-1682 中位数计数的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 超火表白代码,心心(html+css)
- 下一篇: 实战小例子 | 经典坦克大战的pytho
