ただいま~~
爲了在usaco上寫下的宏願。。開始繼續刷hdu了。。。(喂!)
Safe Or Unsafe |
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) |
Total Submission(s): 45 Accepted Submission(s): 20 |
Problem Description
Javac++ 一天在看計算機的書籍的時候,看到了一個有趣的東西!每一串字符都可以被編碼成一些數字來儲存信息,但是不同的編碼方式得到的儲存空間是不一樣的!並且當儲存空間大於一定的值的時候是不安全的!所以Javac++ 就想是否有一種方式是可以得到字符編碼最小的空間值!顯然這是可以的,因爲書上有這一塊內容--哈夫曼編碼(Huffman Coding);一個字母的權值等於該字母在字符串中出現的頻率。所以Javac++ 想讓你幫忙,給你安全數值和一串字符串,並讓你判斷這個字符串是否是安全的?
|
Input
輸入有多組case,首先是一個數字n表示有n組數據,然後每一組數據是有一個數值m(integer),和一串字符串沒有空格只有包含小寫字母組成!
|
Output
如果字符串的編碼值小於等於給定的值則輸出yes,否則輸出no。
|
Sample Input
2 12 helloworld 66 ithinkyoucandoit |
Sample Output
no yes |
樸素的哈夫曼樹……樸素也要知道這樹到底是什麼啊!好吧其實很早就知道它了,上次比賽也遇到了(雖然完全沒看出來),但是這是第一次實現。
hdu的網抽了……明天再貼碼吧。
好睏……答應了某隻要早睡的……
oj修復了~打開step的時候發現多了一個鉤鉤超滿足啊~^-^~~
//safe or unsafe
//hdu 2527
//huffman tree!
//point: when there is only one number, need a particular way
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
struct//each node of the tree
{
int weight;
int parent;//the number of parent
int left;//the number of left child
int right;
}node[60];
int main()
{
int hash[30];//how many time did the character appear in string
int i,j,k;//for loop...as usual
char ch[10000];
int cas;
cin>>cas;
while(cas--)
{
memset(hash,0,sizeof(hash));
int lim;//use the number of tree compare with lim
cin>>lim>>ch;
int len=strlen(ch);
for(i=0;i<len;i++)
hash[ch[i]-96]++;//count the time each character appeared
//a=97
for(i=1,j=1;i<30;i++)
{
if(hash[i])//have this character
{
node[j].weight=hash[i];//creat a node
node[j].parent=node[j].left=node[j].right=0;//inatialize
j++;
}
}
j--;//because the last j we plused didn't use
for(i=j+1;i<2*j;i++)//initialize
node[i].weight=node[i].parent=node[i].left=node[i].right=0;
for(i=j+1;i<2*j;i++)
{
int s1,s2;//two smallest weight,s1<s2
s1=s2=9999999;
int x1,x2;//the node number of s1,s2
for(k=1;k<i;k++)//finde the smallest two
{
if(node[k].weight<s1&&node[k].parent==0)
{//smaller than the smallest
s2=s1;
x2=x1;
s1=node[k].weight;
x1=k;
}
else if(node[k].weight<s2&&node[k].parent==0)
{//smaller than the second smallest
s2=node[k].weight;
x2=k;
}
}
//creat a new node,which is the parent of s1 and s2 and is the sum of two
node[i].left=x1;
node[i].right=x2;
node[x1].parent=i;
node[x2].parent=i;
node[i].weight=node[x1].weight+node[x2].weight;
}
int sum=0;//now let's calculate the sum!
for(i=1;i<=j;i++)
{
int cnt=0;//get the number of layer
k=i;
while(node[k].parent!=0)
{
k=node[k].parent;
cnt++;
}
sum+=cnt*node[i].weight;
}
if(j==1)//the huffman cant solve when you only have one number!
sum=node[1].weight;
/*if you have interest you can use this to get the sum of huffman*/
//cout<<sum<<endl;
//now compare and get the result.finally!
if(sum<=lim)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}
that's it~
寒假第一個ac~紀念下~