codeforces-Three Friends
Three Friends
Three friends are going to meet each other. Initially, the first friend stays at the position x=a, the second friend stays at the position x=b and the third friend stays at the position x=c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the left or by 1 to the right (set x=x−1or x=x+1 ) or even don't change it.
Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let a′ , b′ and c′ be the final positions of the first, the second and the third friend, correspondingly.
Then the total pairwise distance is |a′−b′|+|a′−c′|+|b′−c′|, where |x|is the absolute value of x.
Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.
You have to answer qq independent test cases.
The first line of the input contains one integer qq (1≤q≤1000) — the number of test cases.
The next qq lines describe test cases. The i -th test case is given as three integers a,b and cc (1≤a,b,c≤1e9,1≤a,b,c≤1e9 ) — initial positions of the first, second and third friend correspondingly.
The positions of friends can be equal.
For each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.
题目大意:改题目就是说有三个朋友分别在x=a,x=b,x=c三点上,每一个朋友都可以向左或者向右移动一步或者选择不移动。
求移动(或者不移动)后三者最小的距离(|a′−b′|+|a′−c′|+|b′−c′|)
解析:(1)如果三者在一个点上就输出0,否则就给他们排序
(2)排序后如果三者有两者相同算出其距离,如果距离<=2说明可以变 成0(如1 1 2)否者就sum-=4(如1 1 10可以让1+1 1+1 10-1)
(3)如果以上都不是的话就(让最小的++,最大的--)在算sum;
AC代码:
#pragma GCC optimize(2) #include<bits/stdc++.h> using namespace std; inline int read() {int x=0,f=1;char c=getchar();while(c!='-'&&(c<'0'||c>'9'))c=getchar();if(c=='-')f=-1,c=getchar();while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar();return f*x;} typedef long long ll; const int maxn = 1e6+10; int a[3]; int main() { int t; cin>>t; while(t--){ for(int i=0;i<3;i++){ cin>>a[i]; } if(a[1]==a[0]&&a[1]==a[2]){ printf("0\n"); } else{ sort(a,a+3); ll sum=0; if(a[0]==a[1]||a[1]==a[2]){ sum+=abs(a[0]-a[1])+abs(a[1]-a[2])+abs(a[2]-a[0]); if(sum<=2){ sum=0; } else{ sum-=4; } } else{ a[0]++; a[2]--; sum+=abs(a[0]-a[1])+abs(a[1]-a[2])+abs(a[2]-a[0]); } printf("%d\n",sum); } } return 0; }