Problem HHamiltonian Hypercube
Hypercube graphs are fascinatingly regular, hence you have devoted a lot of time studying themathematics related to them. The vertices of a hypercube graph of dimensionn are all binarystrings of lengthn, and two vertices are connected if they differ in a single position. There aremany interesting relationships between hypercube graphs and error-correcting code.
One such relationship concerns then-bit Gray Code, which is an ordering of the binary stringsof lengthn, defined recursively as follows. The sequence of words in then-bit code first consistsof the words of the(n− 1)-bit code, each prepended by a0, followed by the same words inreverse order, each prepended by a1. The1-bit Gray Code just consists of a0 and a1. Forexample the3-bit Gray Code is the following sequence:
000,001,011,010,110,111,101,100
Now, the n-bit Gray Code forms a Hamiltonian path in then-dimensional hypercube, i.e., a path
that visits every vertex exactly once (see Figure H.1).
010
000
110
100
011
001
111
101
Figure H.1: The3-dimensional hypercube and the Hamiltonian path corresponding to the3-bitGray Code.
You wonder how many vertices there are between the vertices0n(nzeros) and1n(nones) onthat path. Obviously it will be somewhere between2n−1− 1and 2n− 2, since in general0nis thefirst vertex, and1nis somewhere in the second half of the path. After finding an elegant answerto this question you ask yourself whether you can generalise the answer by writing a programthat can determine the number of vertices between two arbitrary vertices of the hypercube, inthe path corresponding to the Gray Code.
Input
The input consists of a single line, containing:
• one integern (1≤ n≤ 60), the dimension of the hypercube
• two binary stringsa andb, both of lengthn, wherea appears beforeb in then-bit GrayCode.
NWERC 2016 Problem H: Hamiltonian Hypercube15
Output
Output the number of code words betweena andb in then-bit Gray Code.Sample Input 1 Sample Output 1
Sample Input 2 Sample Output 2
3 001 111 |
3 |
3 110 100 |
2 |
题解:
由样例可发现,110到000的距离为4.
假设一个码字为s,定义a[i]=a[i-1]^(s[i]-'0');
那么s到0...00的距离为a作为二进制的十进制数。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
#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 pb push_back
#define fi first
#define se second
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
const int maxn=60+10;
char s1[maxn],s2[maxn];
int a[maxn];
ll getpos(char *s,int n)
{
a[0]=s[0]-'0';
rep(i,1,n) a[i]=a[i-1]^(s[i]-'0');
ll ans=0;
rep(i,0,n) ans=ans*2+a[i];
return ans;
}
int main()
{
int n;
scanf("%d%s%s",&n,s1,s2);
ll p1=getpos(s1,n),p2=getpos(s2,n);
printf("%lld\n",p2-p1-1);
return 0;
}