結果

問題 No.861 ケーキカット
ユーザー beetbeet
提出日時 2019-08-09 22:16:24
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 1,757 bytes
コンパイル時間 2,415 ms
コンパイル使用メモリ 204,712 KB
実行使用メモリ 134,500 KB
最終ジャッジ日時 2023-09-26 18:18:54
合計ジャッジ時間 33,989 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 TLE -
testcase_01 TLE -
testcase_02 TLE -
testcase_03 TLE -
testcase_04 TLE -
testcase_05 TLE -
testcase_06 TLE -
testcase_07 TLE -
testcase_08 TLE -
testcase_09 TLE -
testcase_10 TLE -
testcase_11 TLE -
testcase_12 TLE -
testcase_13 TLE -
testcase_14 TLE -
testcase_15 TLE -
testcase_16 TLE -
testcase_17 TLE -
testcase_18 TLE -
testcase_19 TLE -
testcase_20 TLE -
testcase_21 TLE -
testcase_22 TLE -
testcase_23 TLE -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}


struct UnionFind{
  Int n,num;
  vector<Int> r,p;
  UnionFind(){}
  UnionFind(Int sz):n(sz),num(sz),r(sz,1),p(sz,0){iota(p.begin(),p.end(),0);}
  Int find(Int x){
    return (x==p[x]?x:p[x]=find(p[x]));
  }
  bool same(Int x,Int y){
    return find(x)==find(y);
  }
  void unite(Int x,Int y){
    x=find(x);y=find(y);
    if(x==y) return;
    if(r[x]<r[y]) swap(x,y);
    r[x]+=r[y];
    p[y]=x;
    num--;
  }
  Int size(Int x){
    return r[find(x)];
  }
  Int count() const{
    return num;
  }
};

//INSERT ABOVE HERE
signed main(){
  const Int n=5;
  Int cs[n][n];
  for(Int i=0;i<n;i++)
    for(Int j=0;j<n;j++)
      cin>>cs[i][j];

  Int s=(1<<(n*n-1));
  Int ds[n][n]={};

  Int sum=0;
  for(Int i=0;i<n;i++)
    for(Int j=0;j<n;j++)
      sum+=cs[i][j];

  Int ans=sum;
  for(Int i=0;i<n;i++)
    for(Int j=0;j<n;j++)
      chmin(ans,abs(sum-cs[i][j]*2));

  auto idx=[&](Int y,Int x){return y*n+x;};
  vector<Int> dp(s,0);
  for(Int b=0;b<s;b++){
    for(Int i=0;i+1<n*n;i++)
      if((~b>>i)&1) dp[b|(1<<i)]=dp[b]+cs[i/n][i%n];

    Int res=dp[b]+cs[n-1][n-1];
    if(ans<=abs(sum-res*2)) continue;

    for(Int i=0;i<n;i++)
      for(Int j=0;j<n;j++)
        ds[i][j]=(b>>idx(i,j))&1;

    ds[n-1][n-1]=1;
    UnionFind uf(n*n);
    for(Int i=0;i<n;i++){
      for(Int j=0;j<n;j++){
        if(i+1<n&&ds[i][j]==ds[i+1][j]) uf.unite(idx(i,j),idx(i+1,j));
        if(j+1<n&&ds[i][j]==ds[i][j+1]) uf.unite(idx(i,j),idx(i,j+1));
      }
    }
    if(uf.count()==2) ans=abs(sum-res*2);
  }
  cout<<ans<<endl;
  return 0;
}
0