(step5.1.2)hdu 1305(Immediate Decodability——字典樹)
阿新 • • 發佈:2019-01-23
題目大意:輸入一系列的字串,判斷這些字串中是否存在其中的一個字串是另外一個字串的字首。。
如果是,輸出Set 。。 is not immediately decodable
否則輸出Set .. is immediately decodable
說的通俗點,就是判斷一個字串是否是兩外一個字串的字首
解題思路:
這是一道字典樹的題。一開始的時候,我用c/c++來寫,然後是100行寫完了,就是不知道哪裡錯了
這時,我實在忍不住了。直接就用java來寫了
程式碼如下:(注意以下程式碼在submit的時候是需要對格式改一下的。。。但我這裡可懶得改了)
package com.njupt.acm; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Scanner; import java.util.Set; public class HDU_1305 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int counter = 1; while (scanner.hasNext()) { Set set = new HashSet(); String str = scanner.next(); boolean flag = true; set.add(str); while (scanner.hasNext()) { str = scanner.next(); if (str.equals("9")) { if(flag){ System.out.println("Set "+(counter++)+" is immediately decodable"); }else{ System.out.println("Set "+(counter++)+" is not immediately decodable"); } break; } Iterator<String> iter = set.iterator(); while (iter.hasNext()) { String str1 = iter.next(); if (str.startsWith(str1) || str1.startsWith(str)) { flag = false; break; } } if(flag){ set.add(str); } } } } }
以下附上讓人心碎的c/c++程式碼
/* * 1305_1.cpp * * Created on: 2013年8月24日 * Author: Administrator */ #include <iostream> using namespace std; const int maxn = 2; struct node { int count; node* next[maxn]; }; node* root; node* newset() { node* current; current = (node*) malloc(sizeof(node)); int i; for (i = 0; i < maxn; ++i) { current->next[i] = NULL; } current->count = 1; return current; } void insert(char* s) { node* current; int len = strlen(s); if (len == 0) { return; } current = root; int i; for (i = 0; i < len; ++i) { if (current->next[s[i] - '0'] != NULL) { current = current->next[s[i] - '0']; current->count = current->count + 1; } else { current->next[s[i] - '0'] = newset(); current = current->next[s[i] - '0']; } } } int find(char* s) { node* current; int len = strlen(s); if (len == 0) { return 0; } current = root; int i; for (i = 0; i < len; ++i) { if (current->next[s[i] - '0'] != NULL) { current = current->next[s[i] - '0']; } else { return 0; } } return current->count; } int main() { char str[15][15]; int line = 0, count = 1; while (scanf("%s", str[line]) != EOF) { root = newset(); line = 0; bool flag = true; insert(str[line++]); while (scanf("%s", str[line]) != EOF) { if (str[line][0] == '9') { break; }else{ insert(str[line++]); } } int i; for (i = 0; i < line; ++i) { if (find(str[i]) > 1) { flag = false; break; } } if (flag) { printf("Set %d is immediately decodable\n", count++); } else { printf("Set %d is not immediately decodable\n", count++); } } delete root; }