Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- using ll = long long;
- vector<int> dp;
- int check_bit(int val, int bit){
- return (val>>bit)&1;
- }
- pair<int, int> push(string & s,vector<int> bits, int i){
- int ans_mask = 0;
- int ans_steps = 2;
- if(i) if(s[bits[i]] == s[bits[i - 1]]) ans_steps--;
- int left_sz = ans_steps;
- int right_sz = 0;
- int left = i - 1 ;
- int right = i;
- while(left >= 0 && s[bits[left]] == s[bits[i]]) left--, left_sz++;
- while(right <(int)bits.size() && s[bits[right]] == s[bits[i]]) right++, right_sz++;
- int real_l = left;
- int real_r = right;
- while(left_sz && right_sz && left_sz + right_sz > 2){
- real_l = left;
- real_r = right;
- if(left == -1 || right == (int)bits.size()) break;
- left_sz = 0;
- right_sz = 0;
- char ch = s[bits[left]];
- while(left >=0 && ch == s[bits[left]]) left--,left_sz++;
- while(right < (int)bits.size() && s[bits[right]] == ch) right++, right_sz++;
- }
- for(int i=0;i<=real_l;i++){
- ans_mask |= (1<<bits[i]);
- }
- for(int i = real_r; i < (int)bits.size();i++){
- ans_mask |= (1<<bits[i]);
- }
- return {ans_mask, ans_steps};
- }
- void setmin(int & val, int b){
- if(b < val) val = b;
- }
- struct edge{
- int t, st, i;
- edge(int t, int st, int i){
- this->t = t;
- this->st = st;
- this->i = i;
- }
- };
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- dp.assign(1<<14, 2000'000'000);
- string s;
- cin>>s;
- int n = s.length();
- dp[(1<<n) - 1] = 0;
- for(int i=0;i<(1<<n);i++){
- from[i] = i;
- }
- vector<pair<int,int> > masks;
- for(int i=0;i<(1<<(int)(s.length()));i++){
- masks.push_back({__builtin_popcount(i), i});
- }
- vector<edge> g[1<<n];
- sort(masks.begin(), masks.end(), greater<>());
- for(auto p : masks){
- int mask = p.second;
- vector<int> bits;
- for(int i=0;i<n;i++){
- if(check_bit(mask, i))
- bits.push_back(i);
- }
- if((int) bits.size() == 1){
- dp[(1<<n)-1] = min(dp[(1<<n) - 1], dp[mask] + 2);
- continue;
- }
- for(int i = 0; i < (int)bits.size(); i++){
- auto cs = push(s, bits, i);
- if(dp[cs.first] > dp[mask] + cs.second){
- dp[cs.first] = dp[mask] + cs.second;
- g[mask].push_back(edge(cs.first, cs.second, bits[i]));
- }
- }
- }
- cout<<dp[0]<<" ";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement