题意:
水平线上n个村子间有 n-1 条路. 每条路开放一天的价格为 Cost_i.
有 m 天的操作,每天需要用到村子 Ai~Bi 间的道路.
每条路只能开放或关闭一次. (不能重复开关)
求每天的最小花费.
题解:
线段树:维护每条路第一次和最后一次被用到的天数.然后用树状数组维护前缀和,最后输出即可
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <list>
#include <queue>
#include <map>
using namespace std;
#define L(i) i<<1
#define R(i) i<<1|1
#define INF 0x3f3f3f3f
#define pi acos(-1.0)
#define eps 1e-4
#define maxn 200010
#define MOD 1000000007
struct node
{
int l,r;
long long sum;
int lazy;
int Max,Min;
} tree[maxn*4];
int a[200020];
void pushup(int pos)
{
tree[pos].sum = tree[pos<<1].sum + tree[pos<<1|1].sum;
}
void pushdown(int pos)
{
if(!tree[pos].lazy)
return;
tree[pos<<1].Max = max(tree[pos<<1].Max,tree[pos].Max);
tree[pos<<1].Min = min(tree[pos<<1].Min,tree[pos].Min);
tree[pos<<1].lazy = 1;
tree[pos<<1|1].Max = max(tree[pos<<1|1].Max,tree[pos].Max);
tree[pos<<1|1].Min = min(tree[pos<<1|1].Min,tree[pos].Min);
tree[pos<<1|1].lazy = 1;
tree[pos].lazy = 0;
}
void build(int l,int r,int pos)
{
tree[pos].l = l;
tree[pos].r = r;
tree[pos].lazy = 0;
tree[pos].Max = -1;
tree[pos].Min = INF;
if(l == r)
{
//scanf("%I64d",&tree[pos].sum);
return;
}
int mid = (l+r)/2;
build(l,mid,pos<<1);
build(mid+1,r,pos<<1|1);
//pushup(pos);
} //建树 //查询操作
void update(int l,int r,int pos,int cnt)
{
if(tree[pos].l == l && tree[pos].r == r)
{
tree[pos].Max = max(tree[pos].Max,cnt);
tree[pos].Min = min(tree[pos].Min,cnt);
tree[pos].lazy = 1;
return;
}
pushdown(pos);
int mid = (tree[pos].l + tree[pos].r) >> 1;
if(r <= mid)
update(l,r,pos<<1,cnt);
else if(l > mid)
update(l,r,pos<<1|1,cnt);
else
{
update(l,mid,pos<<1,cnt);
update(mid+1,r,pos<<1|1,cnt);
}
//pushup(pos);
} //自上而下更新节点
void query(int l,int pos,int &Max,int &Min)
{
if(tree[pos].l == tree[pos].r)
{
Max = tree[pos].Max;
Min = tree[pos].Min;
return;
}
pushdown(pos);
int mid = (tree[pos].l+tree[pos].r)>>1;
if(l <= mid)
query(l,pos<<1,Max,Min);
else if(l > mid)
query(l,pos<<1|1,Max,Min);
}
int c[200100];
void Update(int x,int num)
{
while(x <= 200100)
{
c[x] += num;
x += x&(-x);
}
}
int getsum(int x)
{
int s = 0;
while(x)
{
s += c[x];
x -= x&(-x);
}
return s;
}
int main()
{
int t,n,m,C = 1;
//scanf("%d",&t);
while(scanf("%d%d",&n,&m) != EOF)
{
memset(c,0,sizeof(c));
build(1,n-1,1);
for(int i = 1; i < n; i++)
scanf("%d",&a[i]);
for(int i = 1; i <= m; i++)
{
int x,y;
scanf("%d%d",&x,&y);
if(x > y)
swap(x,y);
update(x,y-1,1,i);
}
for(int i = 1; i < n; i++)
{
int m1,m2;
query(i,1,m1,m2);
//printf("%d %d\n",m1,m2);
if(m2 != INF)
Update(m2,a[i]);
if(m1 != -1)
Update(m1+1,-a[i]);
}
//printf("saf");
for(int i = 1; i <= m; i++)
printf("%d\n",getsum(i));
}
return 0;
}