Postman
程序员文章站
2022-07-12 11:27:49
...
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=4096
题意:x=0的位置是邮局,邮递员每次可以带k封信,需要回邮局拿信,最后送完信后不必回邮局,求最小路程
C++版本一
题解:
#include <bits/stdc++.h>
using namespace std;
#define LL long long
#define FI first
#define SE second
#define PB push_back
typedef pair<int,LL>PII;
const int N=2e5+7;
const LL INF=1e17,mod=998244353;
int n,m,k;
LL a[N],b[N];
LL ans;
int main()
{
int t;
cin>>t;
while(t--){
ans=0;
scanf("%d%d",&n,&k);
LL x;
int cnt=0,cot=0;
for(int i=1;i<=n;i++){
scanf("%lld",&x);
if(x==0)continue;
if(x<0)a[++cnt]=-x;
else b[++cot]=x;
}
sort(a+1,a+cnt+1);
sort(b+1,b+cot+1);
if(a[cnt]>b[cot]){
ans+=a[cnt];
cnt=max(cnt-k,0);
}
else {
ans+=b[cot];
cot=max(cot-k,0);
}
//cout<<ans<<endl;
while(cnt>0||cot>0){
if(a[cnt]>b[cot]){
ans+=a[cnt]*2;
cnt=max(cnt-k,0);
}
else{
ans+=b[cot]*2;
cot=max(cot-k,0);
}
}
printf("%lld\n",ans);
}
return 0;
}
C++版本二
题解:
1、从两边往中间走;
2、减掉一个绝对值最大的点;
/*
*@Author: STZG
*@Language: C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG
#define RI register int
#define endl "\n"
using namespace std;
typedef long long ll;
//typedef __int128 lll;
const int N=100000+10;
const int M=100000+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
int t,n,m,k,p,l,r,u,v;
ll ans,cnt,flag,temp,sum;
ll c[N];
char str;
struct node{};
int main()
{
#ifdef DEBUG
freopen("input.in", "r", stdin);
//freopen("output.out", "w", stdout);
#endif
//ios::sync_with_stdio(false);
//cin.tie(0);
//cout.tie(0);
srand((unsigned)time(NULL));
scanf("%d",&t);
//t=rand()%(2000)+10000;
while(t--){
scanf("%d%d",&n,&k);
ll maxl=0;
for(int i=1;i<=n;i++){
scanf("%lld",&c[i]);
maxl=max(maxl,abs(c[i]));
}
sort(c+1,c+n+1);
int l=0;
int r=n+1;
ans=0;
for(int i=n;i>=1;i--){
if(c[i]>0){
r=i;
}else{
break;
}
}
for(int i=1;i<=n;i++){
if(c[i]<0){
l=i;
}else{
break;
}
}
for(int i=n;i>=r;i-=k){
ans+=2ll*abs(c[i]);
}
for(int i=1;i<=l;i+=k){
ans+=2ll*abs(c[i]);
}
cout<<ans-maxl<<endl;
}
#ifdef DEBUG
printf("Time cost : %lf s\n",(double)clock()/CLOCKS_PER_SEC);
#endif
//cout << "Hello world!" << endl;
return 0;
}
上一篇: postman Pre-request Script
下一篇: Postman