您的位置:首页 > 其它

HOJ 3287 Cables(贪心)

2017-12-27 13:10 387 查看
Cables


Problem Description


There’s a row of computers in the playing area of CCPC. The ith computer has a coordinate Xi describes the distance between the computer and the exit of
the area. The ith computer also has a value Ai. Ai=0 means the ith computer failed to connect to server. Ai=1 means the ith computer is connected to server.


Mr.Tom has some cables. He can link some computers together with these cables.


If P,Q and Q,R are linked by cables, then we assume that P,R are linked by cables.


If P is connected to server, Mr.Tom linked P,Q together, then Q is connected to server now.

Now Mr.Tom want your help to calculate the sum of the length
of cables he needs to make all computers connected to server.


Input

The first line contains an integer T (1<=T<=10), then T cases follow.

In each case:

The first line contains 1 integers: n (1<=n<=100000), the number of computers.

Then one line contains n integers. The ith integer Xi (0<=Xi<=2^31-1) means the coordinate of the ith computer. We assume that
there will not be two computers that has the same coordinate.
Then one line contains n integers.The ith integer Ai (0<=Ai<=1).
You can find its meaning in the description.


Output

For the i-th case, output one line “Case #i: y”.

y means the sum of the length of cables Mr.Tom needs to make all computers connected to server. If Mr.Tom couldn’t make all
computers connected to server, then y = -1.


Sample Input

2

3

0 4 6

1 0 1

2

2 5

0 0


Sample Output

Case #1: 2

Case #2: -1

题目大意:在一条直线上给你n台电脑,其中有m台和服务器相连,有n-m没连,现在你可以用电线把任意两台电脑相连,相连后可共享服务器,求满足把所有电脑都连接在一起后,所需最短的电线长度·。

心路历程:考试的时候因为很少有人ac所以没看,考完后想了想发现是一道水题(为啥排在最后一个)。
1.由于任何两个计算机都可相连,所以只要有一台计算机和服务器相连就一定有解.
2.现在考虑没有连接上服务器的电脑,可易看出每台电脑至少会引出一条电线(否则则不可能与服务器向量,是断的),所以我们假设在两台与服务器相连的电脑之内有k台电脑,那么它们一共会有k+1个间隔,其中必须选择k个间隔插入网线,所以我们可以得出只要不选最大的那个间隔就好了。
3.注意是选择相邻(不考虑之间不和服务器相连的电脑)的两台和服务器相连的电脑。如果一共只有一台,那么总长度就是区间总长度。

ac代码:
//by Nova
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
//每台电脑有两个指标所以用结构体
struct node{
long long v;
int a;
}p[100010];
//先按坐标排个序
bool cmp(node a, node b){
return a.v < b.v;
}

int main()
{
int cas, num = 1;
scanf("%d", &cas);
while(num <= cas){
int n, i, flag = 0;
scanf("%d",&n);
for(i = 0; i < n; i++) scanf("%lld", &p[i].v);
for(i = 0; i < n; i++){
scanf("%d", &p[i].a);
if(p[i].a == 1) flag = 1;
}
if(flag == 0){
printf("Case #%d: -1\n", num++);
continue;
}
sort(p, p + n, cmp);
long long sum = p[n-1].v - p[0].v, l, r, big = 0;
for(i = 0; i < n; i++){
if(p[i].a == 1){
l = r = i;
break;
}
}
for(i = l + 1; i < n; i++){
big = max(big, p[i].v - p[i-1].v);
if(p[i].a == 1){
sum -= big;
big = 0;
}
}
printf("Case #%d: %d\n", num++, sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  题解 贪心