中位数总结
主要是51nod上的中位数(距离之和最小):
一:1096 距离之和最小:
是一道水题;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<cstdio> #include<cstring> #include<algorithm> using std::sort; int map[10010]; int main() { int n; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&map[i]); sort(map+1,map+1+n); // for(int i=1;i<=n;i++) printf("%d ",map[i]); int t=(n>>1)+1; // printf("std:: %d %d ",t,map[t]); long long ans=0; for(int i=1;i<=n;i++) { if(i<=t) ans+=map[t]-map[i]; else ans+=map[i]-map[t]; } printf("%lld",ans); return 0; }
主体上与上题一样,只是分成三维(tx,ty,tz);
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<cstdio> #include<cstring> #include<algorithm> using std::sort; struct node { int x,y,z; } map[10010]; bool cmpx(node a,node b){return a.x<b.x;} bool cmpy(node a,node b){return a.y<b.y;} bool cmpz(node a,node b){return a.z<b.z;} int abs(int x){if(x>=0) return x;else return -x;} int main() { int n; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d %d %d",&map[i].x,&map[i].y,&map[i].z); sort(map+1,map+1+n,cmpx); int tx=map[(n>>1)+1].x; sort(map+1,map+1+n,cmpy); int ty=map[(n>>1)+1].y; sort(map+1,map+1+n,cmpz); int tz=map[(n>>1)+1].z; long long ans=0; for(int i=1;i<=n;i++) { ans+=abs(map[i].x-tx)+abs(map[i].y-ty)+abs(map[i].z-tz); } printf("%lld",ans); return 0; }
将一变得复杂(类似01背包与完全背包),将每个价值pi的点变成pi个点,那后与一相同(加上简单处理);
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<cstdio> #include<cstring> #include<algorithm> using std::sort; struct node { long long p,x; }map[10010]; bool cmp(node a,node b) {return a.x<b.x;} long long abs(long long x){if(x>=0) return x;return -x;} int main() { int n; scanf("%d",&n); long long sum=0; for(int i=1;i<=n;i++) scanf("%lld %lld",&map[i].x,&map[i].p),sum+=map[i].p; long long t=(sum>>1)+1; sort(map+1,map+1+n,cmp); // for(long long i=1;i<=n;i++) printf("std:: %d %d \n",map[i].x,map[i].p); // printf("std:: %d %d ",t,map[t]); long long tx=0,tsum=0; for(int i=1;i<=n;i++) { tsum+=map[i].p; if(tsum>=t) {tx=map[i].x;break;} } //printf("std:: %d %d %d %d ",sum,t,tx,tzi); long long ans=0; for(int i=1;i<=n;i++) ans=ans+(abs(tx-map[i].x)*map[i].p); printf("%lld",ans); return 0; }
总结:中位数应作为一种思维;