FZU 2136 取糖果 (排序+并查集)

排序,从小到大把每一个数填入数所在的位置。使用并查集求最大的相连的区间长度。然后处理一下久得到答案。

/************************************
 * Author : binwin20                *
 * Blog   : blog.csdn.net/binwin20  *
 ************************************/
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <cmath>
#include <cstring>
#include <iostream>
#include <queue>
#include <map>
#include <stack>
#include <string>
#include <algorithm>
#include <vector>
#include <list>
#include <deque>

#define LL long long
#define DB double
#define SI(a) scanf("%d",&a)
#define SD(a) scanf("%lf",&a)
#define SS(a) scanf("%s",a)
#define PF printf
#define MM(a,b) memset(a,b,sizeof(a))
#define REP(i,a,b) for(int i=a;i<b;i++) 
#define REPD(i,a,b) for(int i=a;i>b;i--)
#define INF 0x3f3f3f3f
#define EPS 1e-8
#define bug puts("bug")
using namespace std;
#define N 100009 
int fa[N];
int finfa(int k){
    if(fa[k]==k) return k;
    return fa[k] = finfa(fa[k]);
}
struct nod{
    int i,w;
    bool operator<(const nod t) const
    {
        return w<t.w;
    }
} re[N];
int s[N];
void init(int k){
    for(int i=0;i<=k;i++)
        s[i] = 1,fa[i] = i;
}
void un(int a,int b){
    int l = finfa(a),r=finfa(b);
    if(l==r) return;
    s[l] += s[r];
    fa[r] = l;
}
int v[N];
int ans[N];
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    #endif
    int cas,n; SI(cas);
    while(cas--) {
        MM(ans,INF);
        MM(v,0);
        SI(n);
        REP(i,1,n+1) {
            SI(re[i].w);
            re[i].i = i;
        }
        REP(i,0,n+1) s[i] = 1,fa[i] = i;        
        sort(re+1,re+n+1);
        REP(i,1,n+1){
            v[re[i].i] = 1;
            int k = re[i].i;
            if(v[k-1]){
                un(k-1,k);
            }
            if(v[k+1]){
                un(k,k+1);
            }
            int c = finfa(k);
            int tmp = s[c];
            ans[tmp] = min(ans[tmp],re[i].w);
        }
        REPD(i,n-1,0)
            ans[i] = min(ans[i],ans[i+1]);
        REP(i,1,n+1)
            PF("%d\n",ans[i]);
    }
    return 0;
}


你可能感兴趣的:(排序,并查集)