HDU

来源:互联网 发布:1.5斤麒麟鞭弹簧垫数据 编辑:程序博客网 时间:2024/06/08 08:21

题意:给n村庄,形成n-1条路,每条路都有一个花费,接下来m天,每天从a村庄运东西到b村庄,a、b之间的路必须打开。每条路只能打开一次和关闭一次。求接下来m天,每天的最小花费。

思路:对于每条路,找出最早的打开时间,和最晚的关闭时间,在这期间,这条路必须打开。用f[i]表示从i开始覆盖的最远的点,用st[i]和en[i]表示第i天打开路的花费和关闭路省下的花费。对于第i天,用并查集来维护最远覆盖的点,如果最远的点没有超过所给区间,st[i]加上这段路的花费,直到超过所给区间。

同理,可以求出en[i]。

#include <cstdio>#include <algorithm>#include <iostream>#include<vector>#include<cmath>#include<set>#include<cstring>#include<map>using namespace std;const int maxn = 21e5 + 10;const int maxt = 100200;const int INF = 0x3f3f3f3f;const int mod = 1e9 + 7;const double pi = acos(-1.0);typedef long long ll;int f[maxn], l[maxn], r[maxn], a[maxn];int st[maxn], en[maxn];int Find(int x){    return x == f[x] ? x : f[x] = Find(f[x]);}void Union(int x, int y){    int t1 = Find(x), t2 = Find(y);    if(t1 != t2){        if(t1 > t2)            f[t2] = t1;        else            f[t1] = t2;    }}int main(){    int n, m;    while(~scanf("%d%d", &n, &m)){        for(int i = 1; i <= n - 1; ++i){            scanf("%d", &a[i]);            f[i] = i;        }        f[n] = n;        memset(st, 0, sizeof st);        memset(en, 0, sizeof en);        for(int i = 1; i <= m; ++i){            scanf("%d%d", &l[i], &r[i]);            if(l[i] > r[i]) swap(l[i], r[i]);            while(true){                int t = Find(l[i]);                if(t >= r[i]) break;                st[i] += a[t];                Union(t, t + 1);            }        }        for(int i = 1; i <= n; ++i) f[i] = i;        for(int i = m; i >= 1; --i){            while(true){                int t = Find(l[i]);                if(t >= r[i]) break;                en[i] += a[t];                Union(t, t + 1);            }        }        int ans = 0;        for(int i = 1; i <= m; ++i){            ans += st[i];            printf("%d\n", ans);            ans -= en[i];        }    }}


1 0