标签:
状态压缩+双向广搜。注意控制时间t。
/* 2209 */ #include <iostream> #include <string> #include <map> #include <queue> #include <set> #include <stack> #include <vector> #include <deque> #include <algorithm> #include <cstdio> #include <cmath> #include <ctime> #include <cstring> #include <climits> #include <cctype> #include <cassert> #include <functional> using namespace std; //#pragma comment(linker,"/STACK:102400000,1024000") #define sti set<int> #define stpii set<pair<int, int> > #define mpii map<int,int> #define vi vector<int> #define pii pair<int,int> #define vpii vector<pair<int,int> > #define rep(i, a, n) for (int i=a;i<n;++i) #define per(i, a, n) for (int i=n-1;i>=a;--i) #define clr clear #define pb push_back #define mp make_pair #define fir first #define sec second #define all(x) (x).begin(),(x).end() #define SZ(x) ((int)(x).size()) #define lson l, mid, rt<<1 #define rson mid+1, r, rt<<1|1 const int maxn = 1<<20; bool mark1[maxn+5]; bool mark2[maxn+5]; char s[25]; int m[25]; void init() { m[0] = 1; rep(i, 1, 25) m[i] = m[i-1]<<1; } void bfs() { queue<int> Q1, Q2; int x = 0, xx; int i, j, k; int t = 0; memset(mark1, false, sizeof(mark1)); memset(mark2, false, sizeof(mark2)); for (i=0; s[i]; ++i) x = (x<<1) + s[i]-‘0‘; if (x == 0) { puts("0"); return ; } int l = i; Q1.push(x); mark1[x] = true; Q2.push(0); mark2[0] = true; int sz1, sz2; while (!Q1.empty() && !Q2.empty()) { ++t; sz1 = SZ(Q1); while (sz1--) { x = Q1.front(); Q1.pop(); for (i=0; i<l; ++i) { xx = x; xx ^= m[i]; if (i) xx ^= m[i-1]; if (i+1 < l) xx ^= m[i+1]; if (mark1[xx]) continue; if (mark2[xx]) { printf("%d\n", t+t-1); return ; } mark1[xx] = true; Q1.push(xx); } } sz2 = SZ(Q2); while (sz2--) { x = Q2.front(); Q2.pop(); for (i=0; i<l; ++i) { xx = x; xx ^= m[i]; if (i) xx ^= m[i-1]; if (i+1 < l) xx ^= m[i+1]; if (mark2[xx]) continue; if (mark1[xx]) { printf("%d\n", t+t); return ; } mark2[xx] = true; Q2.push(xx); } } } puts("NO"); } int main() { ios::sync_with_stdio(false); #ifndef ONLINE_JUDGE freopen("data.in", "r", stdin); freopen("data.out", "w", stdout); #endif init(); while (scanf("%s", s)!=EOF) { bfs(); } #ifndef ONLINE_JUDGE printf("time = %d.\n", (int)clock()); #endif return 0; }
标签:
原文地址:http://www.cnblogs.com/bombe1013/p/4610803.html