Skip to content

Instantly share code, notes, and snippets.

@balamark
Created May 12, 2015 16:58
Show Gist options
  • Select an option

  • Save balamark/043f86d18cadf0051d12 to your computer and use it in GitHub Desktop.

Select an option

Save balamark/043f86d18cadf0051d12 to your computer and use it in GitHub Desktop.
SRM 526 DucksAlignment (div1 250)
#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <typeinfo>
#include <fstream>
using namespace std;
class DucksAlignment {
public:
int minimumTime(vector<string> grid) {
int M=grid.size(), N=grid[0].size();
//assumen N>M
if(M>N){
vector<string> grid1(N, string(M,'-'));
//transpose
for(int c=N-1;c>=0;--c)
for(int r=0;r<M;++r)
grid1[N-1-c][r] = grid[r][c];
grid = grid1;
swap(M,N);
}
vector<int> vc;
int sm=N, lg=0;
for(int r=0;r<M;++r)
for(int c=0;c<N;++c)
if(grid[r][c]=='o')
vc.push_back(r); //center at which row
int sz=vc.size();
sort(vc.begin(), vc.end());//
int ans=2500;
//move all duck to column 'tryc'
for(int tryc=0;tryc<N;++tryc){
int t=0;
for(int row: vc){ //can be more clean if we save column
for(int c=0;c<N;++c) if(grid[row][c]=='o'){
t += abs(c - tryc);
}
}
//try to align all, 0 ~ M-sz
for(int y=0; y+sz<=M;++y){
int columnCost = 0;
for(int i=0;i<sz;++i){
columnCost += abs(vc[i]-(y+i));
}
ans = min(ans, t+columnCost);
}
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment