Skip to content

Instantly share code, notes, and snippets.

@hiroshi-maybe
Created March 3, 2019 15:29
Show Gist options
  • Save hiroshi-maybe/3483918455efc51f78f2b66ebebfbe63 to your computer and use it in GitHub Desktop.
Save hiroshi-maybe/3483918455efc51f78f2b66ebebfbe63 to your computer and use it in GitHub Desktop.
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) for(int i=0;i<(n);++i)
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)
#define REPE(i,n) for(int i=0;i<=(n);++i)
#define FORR(x,arr) for(auto& x:arr)
#define SZ(a) int((a).size())
#define ALL(c) (c).begin(),(c).end()
typedef long long LL;
typedef pair< int , int > II;
typedef unordered_map < int, int > MAPII;
typedef unordered_set < int > SETI;
typedef vector < int > VI;
template<class T> using VV=vector<vector<T>>;
template<class T> using VVV=vector<vector<vector<T>>>;
template<class T> using VVVV=vector<vector<vector<vector<T>>>>;
template<class T> inline T SMIN(T& a, const T b) { return a=(a>b)?b:a; }
template<class T> inline T SMAX(T& a, const T b) { return a=(a<b)?b:a; }
#define MINUS(dp) memset(dp, -1, sizeof(dp))
#define ZERO(dp) memset(dp, 0, sizeof(dp))
template<class Iter> void __kumaerrc(Iter begin, Iter end) { for(; begin!=end; ++begin) { cout<<*begin<<','; } cout<<endl; }
void __kumaerr(istream_iterator<string> it) { (void)it; cout<<endl; }
template<typename T, typename... Args> void __kumaerr(istream_iterator<string> it, T a, Args... args) { cout<<*it<<"="<<a<<", ",__kumaerr(++it, args...); }
template<typename S, typename T> std::ostream& operator<<(std::ostream& _os, const std::pair<S,T>& _p) { return _os<<"{"<<_p.first<<','<<_p.second<<"}"; }
#define __KUMATRACE__ true
#ifdef __KUMATRACE__
#define dump(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); __kumaerr(_it, args); }
#define dumpc(ar) { cout<<#ar<<": "; FORR(x,(ar)) { cout << x << ','; } cout << endl; }
#define dumpC(beg,end) { cout<<"~"<<#end<<": "; __kumaerrc(beg,end); }
#else
#define dump(args...)
#define dumpc(ar)
#define dumpC(beg,end)
#endif
const int Inf=1e7;
int cum[31];
int memo[31][31];
class Solution {
public:
int K;
int f(int l, int r) {
int &res=memo[l][r];
if(res>=0) return res;
int n=r-l;
if(n==1) return res=0;
if((n-1)%(K-1)!=0) return Inf;
VV<int> dp(r-l+1,VI(K+1,Inf));
dp[0][0]=0;
REP(i,r-l)REP(k,K)REP(cnt,r-l) if(i+cnt<=r-l) {
// dump(l,r,i,k,cnt);
SMIN(dp[i+cnt][k+1],dp[i][k]+f(l+i,l+i+cnt)+cum[l+i+cnt]-cum[l+i]);
}
return res=dp[r-l][K];
}
int mergeStones(vector<int>& A, int K) {
MINUS(memo);
this->K=K;
int N=SZ(A);
if(N==1) return 0;
if((N-K)%(K-1)!=0) return -1;
cum[0]=0;
REP(i,N) cum[i+1]=cum[i]+A[i];
int x=(N-K)/(K-1);
if(x<0) return -1;
// int a=f(0,2);
// dump(a);
int res=f(0,N);
return res>=Inf?-1:res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment