1150: [CTSC2007]数据备份Backup
Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 2626 Solved: 1065
[Submit][Status][Discuss]
Description
你在一家 IT 公司为大型写字楼或办公楼(offices)的计算机数据做备份。然而数据备份的工作是枯燥乏味的,因此你想设计一个系统让不同的办公楼彼此之间互相备份,而你则坐在家中尽享计算机游戏的乐趣。已知办公楼都位于同一条街上。你决定给这些办公楼配对(两个一组)。每一对办公楼可以通过在这两个建筑物之间铺设网络电缆使得它们可以互相备份。然而,网络电缆的费用很高。当地电信公司仅能为你提供 K 条网络电缆,这意味着你仅能为 K 对办公楼(或总计2K个办公楼)安排备份。任一个办公楼都属于唯一的配对组(换句话说,这 2K 个办公楼一定是相异的)。此外,电信公司需按网络电缆的长度(公里数)收费。因而,你需要选择这 K 对办公楼使得电缆的总长度尽可能短。换句话说,你需要选择这 K 对办公楼,使得每一对办公楼之间的距离之和(总距离)尽可能小。下面给出一个示例,假定你有 5 个客户,其办公楼都在一条街上,如下图所示。这 5 个办公楼分别位于距离大街起点 1km, 3km, 4km, 6km 和 12km 处。电信公司仅为你提供 K=2 条电缆。
上例中最好的配对方案是将第 1 个和第 2 个办公楼相连,第 3 个和第 4 个办公楼相连。这样可按要求使用 K=2 条电缆。第 1 条电缆的长度是 3km-1km=2km ,第 2 条电缆的长度是 6km-4km=2km。这种配对方案需要总长 4km 的网络电缆,满足距离之和最小的要求。
Input
输入的第一行包含整数n和k,其中n(2 ≤ n ≤100 000)表示办公楼的数目,k(1≤ k≤ n/2)表示可利用
的网络电缆的数目。接下来的n行每行仅包含一个整数(0≤ s ≤1000 000 000), 表示每个办公楼到大街起点处
的距离。这些整数将按照从小到大的顺序依次出现。
Output
输出应由一个正整数组成,给出将2K个相异的办公楼连成k对所需的网络电缆的最小总长度。
Sample Input
5 2
1
3
4
6
12
1
3
4
6
12
Sample Output
4
就是种树啊。
经典题啊
链表维护
把 a,b,c,d,e 变成 a,b+d-c,e 就好了啊
#include<cmath>
#include<ctime>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<vector>
#include<string>
#include<bitset>
#include<queue>
#include<set>
#include<map>
using namespace std;
typedef double db;
typedef long long ll;
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch<='9'&&ch>='0'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
void print(int x)
{if(x<0)putchar('-'),x=-x;if(x>=10)print(x/10);putchar(x%10+'0');}
const int N=100100,inf=0X3f3f3f3f;
struct node
{
int pos,val;
friend bool operator <(const node &x,const node &y)
{return x.val>y.val;}
};
priority_queue<node>q;
bool used[N];
int nt[N],pre[N];
int V[N],p[N];
inline void del(int k)
{
used[k]=1;
nt[pre[k]]=nt[k];
pre[nt[k]]=pre[k];
}
int main()
{
int n=read(),K=read();
register int i;
for(i=1;i<=n;++i) p[i]=read();
for(i=1;i<=n+1;++i)
nt[i]=i+1,pre[i]=i-1;
p[0]=p[1]-inf;p[n+1]=p[n]+inf;
for(i=1;i<=n+1;++i)
V[i]=p[i]-p[i-1],q.push((node){i,p[i]-p[i-1]});
int ans(0);
while(K--)
{
while(used[q.top().pos]) q.pop();
node u(q.top());q.pop();
ans+=u.val;
u.val*=-1;
u.val+=V[nt[u.pos]];
u.val+=V[pre[u.pos]];
V[u.pos]=u.val;
V[nt[u.pos]]=V[pre[u.pos]]=0;
del(nt[u.pos]);del(pre[u.pos]);
q.push(u);
}
cout<<ans<<endl;
return 0;
}
/*
5 2
1
3
4
6
12
4
*/