日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

牛客 - 仓库选址(中位数+思维)

發布時間:2024/4/11 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 牛客 - 仓库选址(中位数+思维) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目鏈接:點擊查看

題目大意:給出一個 n * m 的矩陣,每個格子中都有一個數字,代表需要運貨的次數,現在需要選出一個點作為倉庫,使得累計運貨的路程最短

題目分析:真沒想到數據水到能讓 n^4 的算法水過去,多的就不說了,一會會掛暴力的頭鐵代碼的

重點想說一下如何用中位數解決這個問題,關于中位數處理類似的一維問題,我們只需要求出 x 軸上的中位數,選取該位置作為倉庫肯定是最優的了,那么在二維平面該如何選擇呢,其實也是同理,我們只需要沿著行開始遍歷,確定下來 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; }

?

總結

以上是生活随笔為你收集整理的牛客 - 仓库选址(中位数+思维)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。