Analysis: In fact, it is to find a point in the rectangle to other points of the distance weighted minimum
Method One:
The weighted distance from each point to the other points is then minimized. Since there are m*n points, the weighted distance for each point is O (m*n), so the overall time complexity is O (m*m*n*n).
Method Two:
First the preprocessing, calculate how many points each row has, how many points each column has, and then calculate to move the points of the other rows to the weighted distance required by my line, and move the points of the other columns to the weighted distance of my column,
Then for each point, calculate the cost of moving to its own line + the cost of the column and find the minimum. Time complexity O (m*n).
Code see below, Calcmin is method one, Calcdiego is method two.
#include <cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespacestd;#defineMax_size 500intArr[max_size][max_size];intSumofrow[max_size];intSumofcol[max_size];intCostofrow[max_size];intCostofcol[max_size];intRtnrow;intRtncol;intCalccost (intRowintColintXinty) { intCost =0; for(inti =0; i < row; i++) { for(intj =0; J < Col; J + +) { if(Arr[i][j]! =0) { cost+ = (ABS (x-i) + ABS (Y-J)) *Arr[i][j]; } } } returnCost ;}voidCalcmin (intRowintCol) { Long LongMincost =Llong_max; Long LongTmpcost =0; for(inti =0; i < row; i++) { for(intj =0; J < Col; J + +) {Tmpcost=calccost (Row, col, I, J); if(Tmpcost <mincost) {Mincost=Tmpcost; Rtnrow=i; Rtncol=J; } } }}voidCalcdiego (intRowintCol) { for(inti =0; i < row; i + +) {Sumofrow[i]=0; Costofrow[max_size]=0; } for(intj =0; J < Col; J + +) {Sumofcol[j]=0; Costofcol[max_size]=0; } for(inti =0; i < row; i + +) { for(intj =0; J < Col; J + +) {Sumofrow[i]+=Arr[i][j]; SUMOFCOL[J]+=Arr[i][j]; } } for(inti =0; i < row; i + +)//Cost- Moving row J to row I { for(intj =0; J < Row; J + +) { if(i = = J | | sumofrow[j] = =0) Continue; Costofrow[i]+ = (ABS (j-i)) *Sumofrow[j]; } } for(inti =0; I < col; i + +)//Cost- Moving Col J to Col I { for(intj =0; J < Col; J + +) { if(i = = J | | sumofcol[j] = =0) Continue; Costofcol[i]+ = (ABS (j-i)) *Sumofcol[j]; } } intCost =Int_max; for(inti =0; i < row; i + +) { for(intj =0; J < Col; J + +) { if(Costofrow[i] + costofcol[j] <Cost ) { Cost= (Costofrow[i] +Costofcol[j]); Rtnrow=i; Rtncol=J; } } }}intMain () {intI, J; intRow, col; cout<<"int_max\t"<< Int_max <<Endl; cout<< (500ull* -*500000) <<Endl; while(SCANF ("%d%d", &row, &col) = =2) { for(i =0; i < row; i++) { for(j =0; J < Col; J + +) {scanf ("%d", &Arr[i][j]); } } //printf ("calc\n");calcmin (Row, col); printf ("%d%d\n", Rtnrow, Rtncol); Calcdiego (Row, col); printf ("%d%d\n", Rtnrow, Rtncol); } return 0;}
Amazon online test Topic Amazon