【CodeForce 1299C】Water Balance

Water Balance :

題意:

抽象版本:給出一段序列n,有一種操作:使得[L,R]內區間的所有數,變爲區間的平均數。這個操作可以使用無數次,問最後得到最小字典序的序列是多少?

三組樣例自行體會:

4
7 5 5 7
5.666666667
5.666666667
5.666666667
7.000000000


5
7 8 8 10 12
7.000000000
8.000000000
8.000000000
10.000000000
12.000000000


10
3 9 5 5 1 7 5 3 8 7
3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000

題目思路:

思維好題,首先證明一個結論。

如果區間S1=[x1,y1]的平均值爲z1,區間S2=[x2,y2]的平均值爲z2,如果z2<z1,那麼如果將S2合併到S1中,S1的平均值會變小。

證:

Supposed\ the\ length\ of\ s1\ is\ N,\ and\ the\ length\ of\ s2\ is\ P\\ z1 = \frac{sum1}{N}\\ z2=\frac{sum2}{P}\\ z3=\frac{z1*N+z2*P}{P+N}\\

顯然 :

1.z2 == z1 那麼平均值不變

2.z2>z1 就會使得平均值變大

3.z2<z1合併後會使得平均值變小

所以根據這個性質,就可把這個題寫掉了(2100分感覺2000分都在這個小學數學上)

遍歷N個數字,因爲要讓前面的最小所以,判斷新來數字是否可以將前面的變小,如果則融入到前面的序列中,繼續判斷新序列能否將再前面的平均值變小,依次進行——也就是單調棧思想了。

Code:

/*** keep hungry and calm CoolGuang!***/
#pragma GCC optimize(2)
//#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pp;
const ll INF=1e18;
const int maxn=1e6+6;
const int mod=1e9+7;
const double eps=1e-9;
inline bool read(ll &num)
{char in;bool IsN=false;
in=getchar();if(in==EOF) return false;while(in!='-'&&(in<'0'||in>'9')) in=getchar();if(in=='-'){ IsN=true;num=0;}else num=in-'0';while(in=getchar(),in>='0'&&in<='9'){num*=10,num+=in-'0';}if(IsN) num=-num;return true;}
ll n,m;
struct node{
    int len;
    double w;
    double sum;
}st[maxn];
ll num[maxn];
int main()
{
    read(n);
    for(int i=1;i<=n;i++) read(num[i]);
    int s=0;
    for(int i=1;i<=n;i++){
        st[++s].w=num[i]*1.0;
        st[s].len=1;
        st[s].sum=num[i]*1.0;
        while(s>1&&st[s].w<st[s-1].w){
            st[s-1].sum+=st[s].sum;
            st[s-1].len+=st[s].len;
            st[s-1].w=st[s-1].sum/st[s-1].len*1.0;
            s--;
        }
    }
    for(int i=1;i<=s;i++){
        for(int k=1;k<=st[i].len;k++)
            printf("%.9f\n",st[i].w);
    }
    return 0;
}
/**
10 5
1 7
2 6
2 10
3 7
4 8
5 9
0 0
**/

這個題的思路確實強,以後多注意運用數學

還有 ,數論真的該好好補補了 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章