Lisa’s Puzzle | ||
[ Submit Code ] [ Top 20 Runs ] | ||
Acceteped : 18 | Submit : 145 | |
Time Limit : 1000 MS | Memory Limit : 65536 KB | |
Description | ||
Lisa’s Puzzle题目描述5的二进制是101,13的二进制是1101,所以在二进制上,5是13的后缀。Lisa获得了一个长长的正整数列表,她想知道在列表中每一个数是列表中多少个其他数的后缀? 输入第一行是一个整数 N,1≤N≤100000 ,表示整数的个数。 以后N行,每行一个正整数,每个都可以使用一个32位int表示,而且所有的数都是唯一的。 输出每个整数对应的结果输出一行, 样例输入5 5 13 1 2 3 样例输出1 0 3 0 0 | ||
Sample Input | ||
Sample Output | ||
Source | ||
[ Submit Code ] [ Top 20 Runs ] |
思路:与哈夫曼树相似。就是构造一棵二叉树,使得每个节点的左孩子节点代表二进制中的0,相应地,右孩子节点代表二进制中的1。这样,将每个数化为二进制数,按树的结构存储就能够确立一条路径,这条路径就代表一个数,这样只要其他数对应的路径经过某一个数对应的路径,那么某一个数就是其他数的后缀了,因此,在每个节点存储经过这个节点的路径数,然后将每个数的对应节点找到(即每个数对应路径的终点),输出存储的这个信息即可,详见代码。// 根据这个思路用C++写,T到死。最后是看别人用JAVA写的通过率比较高,就投机取巧试了试,结果过了。
AC代码如下:
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
while (in.hasNext()){
int n = in.nextInt();
Node huff[] = new Node[n];
Node root = new Node(null, null, 0);
for (int i=0; i<n; ++i){
int num = in.nextInt();
String str = Integer.toBinaryString(num);
Node current = root;
for (int j=str.length()-1; j>=0; --j){
if (str.charAt(j) == '0'){
if (current.left == null){
current.left = new Node(null, null, 0);
current = current.left;
}
else{
current = current.left;
++current.cnt;
}
}
else{
if (current.right == null){
current.right = new Node(null, null, 0);
current = current.right;
}
else{
current = current.right;
++current.cnt;
}
}
}
huff[i] = current;
}
for (int i=0; i<n; ++i)
System.out.println(huff[i].cnt);
}
in.close();
}
static class Node{
public Node left, right;
public int cnt;
public Node(Node left, Node right, int cnt){
this.left = left;
this.right = right;
this.cnt = cnt;
}
}
}
刚问了别人这题C++写法。于是才知道,以前一直T,是因为用了链表,只要将链表实现改为数组实现就可以了,思路是一模一样的。
附上C++代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
struct node{
int l, r, cnt;
node(){
l = r = -1;
cnt = 0;
}
} huff[maxn<<3];
int ans[maxn];
int n;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
scanf("%d", &n);
int m, t, cnt=0;
for (int i=0; i<n; ++i){
scanf("%d", &m);
t = 0;
while (m){
if (m & 1){
if (huff[t].r == -1){
huff[t].r = ++cnt;
t = cnt;
}
else{
t = huff[t].r;
++(huff[t].cnt);
}
}
else{
if (huff[t].l == -1){
huff[t].l = ++cnt;
t = cnt;
}
else{
t = huff[t].l;
++(huff[t].cnt);
}
}
m >>= 1;
}
ans[i] = t;
}
for (int i=0; i<n; ++i)
printf("%d\n", huff[ans[i]].cnt);
return 0;
}