Some major cities have subway systems in the form of a tree, i.e. between any pair of stations, there is one and only one way of going by subway. Moreover, most of these cities have a unique central station. Imagine you are a tourist in one of these cities and you want to explore all of the subway system. You start at the central station and pick a subway line at random and jump aboard the subway car. Every time you arrive at a station, you pick one of the subway lines you have not yet travelled on. If there is none left to explore at your current station, you take the subway line back on which you first came to the station, until you eventually have travelled along all of the lines twice,once for each direction. At that point you are back at the central station. Afterwards, all you remember of the order of your exploration is whether you went further away from the central station or back towards it at any given time, i.e. you could encode your tour as a binary string, where 0 encodes taking a subway line getting you one station further away from the central station, and 1 encodes getting you one station closer to the central station.
Input
On the first line of input is a single positive integer n, telling the number of test scenarios to follow.Each test scenario consists of two lines, each containing a string of the characters '0' and '1' of length at most 3000, both describing a correct exploration tour of a subway tree system.
Output
exploration tours of the same subway tree system, or the text "different" if the two strings cannot be exploration tours of the same subway tree system.
Sample Input
2 0010011101001011 0100011011001011 0100101100100111 0011000111010101
Sample Output
same different
题意:有根树,然后0表示访问儿子,1表示返回父亲。
题解:只需要将每个节点的子树大小求出,排序,判断是否一样就可以了,然而我是hash的,十分巧妙。
1 #include<cmath> 2 #include<cstdio> 3 #include<vector> 4 #include<cstring> 5 #include<iostream> 6 #include<algorithm> 7 #define ll long long 8 using namespace std; 9 10 int l; 11 string a,b; 12 vector<int>e[3005]; 13 unsigned ll H[3005]; 14 int fa[3005]; 15 16 bool cmp(int a,int b){return H[a]>H[b];} 17 18 void dfs(int x) 19 { 20 H[x]=19; 21 for(int i=0;i<e[x].size();i++) 22 dfs(e[x][i]); 23 sort(e[x].begin(),e[x].end(),cmp);//为什么排序,因为根据有序来hash,不然是无法比较 24 for(int i=0;i<e[x].size();i++) 25 H[x]=H[x]*9875321+H[e[x][i]]*197; 26 } 27 unsigned ll cal(string a) 28 { 29 l=a.length(); 30 int now=1,cnt=1; 31 for(int i=0;i<l;i++) 32 if(a[i]=='0') 33 { 34 e[now].push_back(++cnt); 35 fa[cnt]=now,now=cnt; 36 } 37 else now=fa[now]; 38 dfs(1); 39 for(int i=1;i<=cnt;i++) 40 e[i].clear(); 41 return H[1]; 42 } 43 int main() 44 { 45 int cas;scanf("%d",&cas); 46 while(cas--) 47 { 48 cin>>a;cin>>b; 49 if(cal(a)==cal(b))puts("same"); 50 else puts("different"); 51 } 52 }