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
//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;
}