牛客 - 仓库选址(中位数+思维)
生活随笔
收集整理的這篇文章主要介紹了
牛客 - 仓库选址(中位数+思维)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個 n * m 的矩陣,每個格子中都有一個數字,代表需要運貨的次數,現在需要選出一個點作為倉庫,使得累計運貨的路程最短
題目分析:真沒想到數據水到能讓 n^4 的算法水過去,多的就不說了,一會會掛暴力的頭鐵代碼的
重點想說一下如何用中位數解決這個問題,關于中位數處理類似的一維問題,我們只需要求出 x 軸上的中位數,選取該位置作為倉庫肯定是最優(yōu)的了,那么在二維平面該如何選擇呢,其實也是同理,我們只需要沿著行開始遍歷,確定下來 x 的坐標,然后再沿著列開始遍歷,確定下來 y 的坐標,這樣就可以確定下來倉庫的具體位置,剩下的 n^2 計算出答案就好了
代碼:
中位數:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=110;LL a[N][N];int main() { #ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); #endif // ios::sync_with_stdio(false);int w;cin>>w;while(w--){int n,m;scanf("%d%d",&m,&n);LL sum=0;for(int i=1;i<=n;i++)for(int j=1;j<=m;j++){scanf("%lld",&a[i][j]);sum+=a[i][j];}int x,y;LL mid=sum+1>>1;LL now=0;for(int i=1;i<=n;i++){for(int j=1;j<=m;j++)now+=a[i][j];if(now>=mid){x=i;break;}}now=0;for(int j=1;j<=m;j++){for(int i=1;i<=n;i++)now+=a[i][j];if(now>=mid){y=j;break;}}LL ans=0;for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)ans+=a[i][j]*(abs(i-x)+abs(j-y));printf("%lld\n",ans);}return 0; }暴力:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=110;LL a[N][N];int main() { #ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); #endif // ios::sync_with_stdio(false);int w;cin>>w;while(w--){int n,m;scanf("%d%d",&m,&n);for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)scanf("%lld",&a[i][j]);LL ans=1e18;for(int i=1;i<=n;i++)for(int j=1;j<=m;j++){LL temp=0;for(int ii=1;ii<=n;ii++)for(int jj=1;jj<=m;jj++)temp+=a[ii][jj]*(abs(i-ii)+abs(j-jj));ans=min(ans,temp);}printf("%lld\n",ans);}return 0; }?
總結
以上是生活随笔為你收集整理的牛客 - 仓库选址(中位数+思维)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牛客 - 货物种类(差分)
- 下一篇: XJOJ - 路径数(最短路+最短路路径