1. 程式人生 > 其它 >【題解】CF1585C Minimize Distance

【題解】CF1585C Minimize Distance

題意

在數軸上有 \(n\) 個點,有 \(n\) 個人和一輛車。每個人要由車送去一個點。
車一次最多能載 \(k\) 個人。送完人後不用返回。求最小距離。

Sol

將數軸左邊與右邊的點分開處理。
每次都處理當前最靠右(左)且沒到過的點。
那麼開兩個陣列分別存下正座標和負座標,暴力列舉即可。
最後記得把返程的路減掉。
時間複雜度 \(O(n \log n)\),瓶頸在於排序。

Code

//LYC_music yyds!
#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0)
#define lowbit(x) (x&(-x))
#define int long long
using namespace std;
inline char gc()
{
	static char buf[1000000],*p1=buf,*p2=buf;
	return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
}
int read()
{
	int pos=1,num=0;
	char ch=getchar();
	while (!isdigit(ch))
	{
		if (ch=='-') pos=-1;
		ch=getchar();
	}
	while (isdigit(ch))
	{
		num=num*10+(int)(ch-'0');
		ch=getchar();
	}
	return pos*num;
}
void write(int x)
{
	if (x<0)
	{
		putchar('-');
		write(-x);
		return;
	}
	if (x>=10) write(x/10);
	putchar(x%10+'0');
}
void writesp(int x)
{
	write(x);
	putchar(' ');
}
void writeln(int x)
{
	write(x);
	putchar('\n');
}
const int N=2e5+10;
int n,m,n1,n2,ans,a[N],b[N];
signed main()
{
	int T=read();
	while (T--)
	{
		n=read(); m=read(); n1=n2=ans=0;
		for (int i=1;i<=n;i++)
		{
			int x=read();
			if (x>0) a[++n1]=x;
			else b[++n2]=-x;
		}
		sort(a+1,a+n1+1);
		sort(b+1,b+n2+1);
		for (int i=n1;i>=1;i-=m)
			ans+=a[i]*2;
		for (int i=n2;i>=1;i-=m)
			ans+=b[i]*2;
		if (n1&&n2) ans-=max(a[n1],b[n2]);
		else if (n1) ans-=a[n1];
		else if (n2) ans-=b[n2];
		writeln(ans);
	}
}