1. 程式人生 > >P3819 松江1843路

P3819 松江1843路

pre getchar 接下來 整數 oid getc 所有 algorithm 全部

題目描述

淶坊路是一條長L米的道路,道路上的坐標範圍從0到L,路上有N座房子,第i座房子建在坐標為x[i]的地方,其中住了r[i]人。

松江1843路公交車要在這條路上建一個公交站,市政府希望讓最多的人得到方便,因此希望所有的每一個的居民,從家到車站的距離的總和最短。

公交站應該建在哪裏呢?

輸入輸出格式

輸入格式:

第一行輸入L、N。

接下來N行,每行兩個整數x[i]和r[i]。

輸出格式:

一個整數,最小的每個人從家到車站的距離的總和。

輸入輸出樣例

輸入樣例#1:
100 3
20 3
50 2
70 1
輸出樣例#1:
110

輸入樣例#2:
100 2
0 1
100 10
輸出樣例#2:
100
輸入樣例#3:
10000000000 5
3282894320 391
4394338332 929
6932893249 181
7823822843 440
9322388365 623
輸出樣例#3:
5473201404068

說明

樣例解釋1

當建在坐標40的時候,所有人距離車站的距離總和為 |20−40|×3+|50−40|×2+|70−40|×1=110。

數據範圍和約定

對於10%的數據,1≤N≤50,R[i]=1。

對於30%的數據,1≤N≤100,R[i]≤10,1≤L≤1000。

對於70%的數據,1≤N≤1000,R[i]≤100,1≤L≤10^6。

對於全部數據,1≤L≤10^10,1≤N≤10^5,0≤x[i]≤L,1≤r[i]≤1000

我們可以證明出:

1.最小的點一定是建在某個房子上。,

2.這個房子是重點!

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cmath>
 5
#include<queue> 6 #include<algorithm> 7 #define lli long long int 8 using namespace std; 9 const int MAXN=100001; 10 void read(lli &n) 11 { 12 char c=+;lli x=0;bool flag=0; 13 while(c<0||c>9) 14 {c=getchar();if(c==-)flag=1;} 15 while(c>=0&&c<=9) 16 {x=x*10+(c-48);c=getchar();} 17 flag==1?n=-x:n=x; 18 } 19 lli l,n; 20 struct node 21 { 22 lli x,pep; 23 }a[MAXN]; 24 lli tot; 25 lli comp(const node &a,const node &b) 26 { 27 return a.x<b.x; 28 } 29 int main() 30 { 31 read(l);read(n); 32 for(lli i=1;i<=n;i++) 33 { 34 read(a[i].x);read(a[i].pep); 35 tot+=a[i].pep; 36 } 37 tot=(tot+1)/2; 38 39 sort(a+1,a+n+1,comp); 40 41 lli now=0; 42 lli mid=0; 43 for(lli i=1;i<=n;i++) 44 { 45 now+=a[i].pep; 46 if(now>=tot) 47 { 48 mid=i; 49 break; 50 } 51 } 52 lli ans=0; 53 for(lli i=1;i<=n;i++) 54 { 55 ans+=(a[i].pep*abs(a[mid].x-a[i].x)); 56 } 57 printf("%lld",ans); 58 return 0; 59 }

P3819 松江1843路