【Grids2418】Hardwood Species解题报告+代码

#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<iostream>
//#define INPUT
/**
    Problem: Grids2418 - Hardwood Species
    Begin Time: 7:30 p.m. 29th/2/2012
    End Time: 2012-02-29 21:35:04
    Cost Time: 2Hours 5Mins
    思路:
    就是一个模拟map<string,int>的过程,具体看下面
    对于每个tree
    1)存在,则二分查找找到对应的tree,count++
    2)不存在,则插入一个结点
    //
    记得要记录一个指向当前数组该插入位置的指针p
    p同时也是不同种tree的数目,但是这个意义在这里没什么用
    树木的总数total要用double类型,
    输出千万记得G++里面是%f
    以上
*/
using namespace  std;
///题目要求其实很简单,用map完全可以水过去
///但是我们这里不让用STL,坑爹啊
///定义一个struct,有name和count,每次找到name之后count++;
///函数1:findEle(string name):bool
///函数2:insertEle(string name)
///函数3:sortSpecies(),这个根据字符串排序,应该是基数排序!
///函数4:increEle(string name);
///函数5:isEql(string,string)
///大概就是这样
const int MAX_SIZE = 10010;
struct _tree
{
    int count;
    char name[35];
};
_tree trees[MAX_SIZE];
int  p_trees = 0;
int findEle(char* name,int range);
void insertEle(char* name,int range);
void increEle(int p);
void sortEle(int range);
int main(int argc,char* argv[])
{
    char buf[35];
    double total = 0;
    int range = 0;
  //  freopen("b:\\acm\\grids2418\\input.txt","r",stdin);
    while(gets(buf) != NULL)
    {
        int k = findEle(buf,p_trees);
        if( k == -1)
        {
            insertEle(buf,p_trees);
            sortEle(p_trees);
        }
        else
            increEle(k);
        total += 1;
    }
    for(int i = 0 ; i < p_trees ; i++)
    {
        printf("%s %.4f\n",trees[i].name,trees[i].count * 100 / total);
    }
    return 0;
}
int comp(const void *a,const void *b)
{
    _tree node1,node2;
    int k = 0;
    node1 = *(_tree*)a;
    node2 = *(_tree*)b;
    k = strcmp(node1.name,node2.name);
    return k;
}
void sortEle(int range)
{
    //
    qsort(trees,range,sizeof(_tree),comp);
}
void increEle(int p)
{
    trees[p].count++;
}
void insertEle(char* name,int range)
{
    //trees[p_trees].name = name;
    strcpy( trees[p_trees].name,name);
    trees[p_trees].count = 1;
    p_trees++;
}
int isEql(const char* name1,const char* name2)
{
    int k = strcmp(name1,name2);
    return k;
    ///That
    ///The,后者e>a,所以The > That
}
int findEle(char* name,int range)
{
////二分查找,在trees里找
    int l = 0 , r = range;
    int mid = (l + r ) / 2;
    int res = -1;
    while( l <= r )
    {
        int t = isEql(trees[mid].name,name);
        if( t > 0 ) ///trees[mid].name > name
            {
                r = mid - 1;
                mid = ( l + r ) /2;
            }
        if( t < 0 )  ///trees[mid].name < name
            {
                l = mid + 1;
                mid = ( l + r ) / 2;
            }
        if ( t == 0 )
            {
                res = mid;
                break;
            }
    }
    return res;
}


你可能感兴趣的:(String,struct,tree,null)