problem url: http://acm.timus.ru/problem.aspx?space=1&num=1025
this should be a sorting question, I used tried using binary sort tree to sort the given vote group serials and print the least half(+1) out(I omit the memory cleanup code):
/*
URAL 1025
AC: time:0.001s memory: 259 KB
using linked Binary Sort Tree
*/
#include < cstdio >
#include < iostream >
using namespace std;
typedef struct BSTNode
{
int fornum;
struct BSTNode * lc;
struct BSTNode * rc;
}BSTNode, * BSTTree;
// global vars
BSTTree g_tree = NULL;
int N = 0 ; // VOTE group number
int minN = 0 ;
int cnt = 0 ; // the counter used to count the min vote number
int sum = 0 ;
void InsertNode(BSTTree * root, int fornum);
void TraverseTree(BSTTree root);
void main()
{
int i = 0 ;
int curgp = 0 ; // record current group's size
scanf( " %d " , & N);
minN = ( int )N / 2 + 1 ;
for (i = 0 ;i < N; ++ i)
{
scanf( " %d " , & curgp);
InsertNode( & g_tree, ( int )(curgp / 2 ) + 1 );
}
// traverse the tree and calculate the min value
TraverseTree(g_tree);
}
void InsertNode(BSTTree * root, int fornum)
{
if (( * root) == NULL)
{
* root = (BSTNode * )malloc( sizeof (BSTNode));
( * root) -> lc = ( * root) -> rc = NULL;
( * root) -> fornum = fornum;
}
else
{
if (fornum < ( * root) -> fornum)
{
InsertNode( & (( * root) -> lc) , fornum);
} else
{
InsertNode( & (( * root) -> rc), fornum);
}
}
}
void TraverseTree(BSTTree root)
{
if (cnt >= minN) return ;
if (root == NULL) return ;
TraverseTree(root -> lc);
sum += root -> fornum;
++ cnt;
if (cnt == minN)
{
printf( " %d " , sum);
return ;
}
TraverseTree(root -> rc);
}
URAL 1025
AC: time:0.001s memory: 259 KB
using linked Binary Sort Tree
*/
#include < cstdio >
#include < iostream >
using namespace std;
typedef struct BSTNode
{
int fornum;
struct BSTNode * lc;
struct BSTNode * rc;
}BSTNode, * BSTTree;
// global vars
BSTTree g_tree = NULL;
int N = 0 ; // VOTE group number
int minN = 0 ;
int cnt = 0 ; // the counter used to count the min vote number
int sum = 0 ;
void InsertNode(BSTTree * root, int fornum);
void TraverseTree(BSTTree root);
void main()
{
int i = 0 ;
int curgp = 0 ; // record current group's size
scanf( " %d " , & N);
minN = ( int )N / 2 + 1 ;
for (i = 0 ;i < N; ++ i)
{
scanf( " %d " , & curgp);
InsertNode( & g_tree, ( int )(curgp / 2 ) + 1 );
}
// traverse the tree and calculate the min value
TraverseTree(g_tree);
}
void InsertNode(BSTTree * root, int fornum)
{
if (( * root) == NULL)
{
* root = (BSTNode * )malloc( sizeof (BSTNode));
( * root) -> lc = ( * root) -> rc = NULL;
( * root) -> fornum = fornum;
}
else
{
if (fornum < ( * root) -> fornum)
{
InsertNode( & (( * root) -> lc) , fornum);
} else
{
InsertNode( & (( * root) -> rc), fornum);
}
}
}
void TraverseTree(BSTTree root)
{
if (cnt >= minN) return ;
if (root == NULL) return ;
TraverseTree(root -> lc);
sum += root -> fornum;
++ cnt;
if (cnt == minN)
{
printf( " %d " , sum);
return ;
}
TraverseTree(root -> rc);
}