pku2418水题map--自己写BST

http://poj.org/problem?id=2418

 

题意:输入很多串,最后按字典序输出串和出现的频率

 

分析:本来来练BST的,顺便用map一下,发现map还不熟悉。。

string 行输入写法:while(getline(cin, b))

map也可以自定义key的结构类型struct,而且加等号了相当于multi_map了。。

 

这题很奇怪。。c++能AC,但g++WA了。。。。--!!!终于发现原因了,G++浮点型标准输出是%f而不是%lf,这里可能会导致wa。。。这题就是这样的。。。。

但是G++在这题的速度是C++的8倍。。

g++是GNU的编译器,c++是编程语言。

 

代码:

BST。。没有删除操作很水。。。

#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <string.h>
#include <map>
using namespace std;

const int N=10010;
char s[35];
int sum;
struct node
{
	char s[35];
	int cnt;
	node *lchild, *rchild;
	node()
	{
		cnt = 0;
		lchild = NULL;
		rchild = NULL;
	}
}*a;

void insert(node *a)
{
	if(a->cnt==0)
	{
		strcpy(a->s, s);
		a->cnt = 1;
		return;
	}
	int i=strcmp(a->s, s);
	if(i==0)
	{
		a->cnt++;
		return;
	}
	if(i>0)
	{
		if(a->lchild==NULL)
			a->lchild = new node;
		insert(a->lchild);
	}
	else
	{
		if(a->rchild==NULL)
			a->rchild = new node;
		insert(a->rchild);
	}
}

void dfs(node *a)
{
	if(a->lchild!=NULL)
		dfs(a->lchild);
	printf("%s %.4lf\n", a->s, (double)a->cnt*100/sum);
	if(a->rchild!=NULL)
		dfs(a->rchild);
}

int main()
{
	node head, *a=&head;
	sum = 0;
//	freopen("1.in", "r", stdin);
	while(gets(s))
	{
		insert(a);
		sum++;
	}
	dfs(a);
	return 0;
}


 

 

代码:

map

/*
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <string.h>
#include <map>
using namespace std;

map<string, int> a;
map<string, int>::iterator it;

int main()
{
	string b;
	int i, j, t, cnt=0;
	//freopen("1.in", "r", stdin);
	while(getline(cin, b)) //string输入的好帮手。。。
	{
		a[b]++;
		cnt++;
	}
	for(it=a.begin(); it!=a.end(); it++)
	{
		printf("%s %.4lf\n", (*it).first.c_str(), (double)(*it).second/cnt*100);
	}

	return 0;
}
*/


#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <string.h>
#include <map>
using namespace std;

const int N=10010;
struct node1
{
	char s[35];
}b;

struct cmp 
{
	bool operator()(const node1 &a, const node1 &b) const //注意这三个const都不能掉。。。
	{
		//return strcmp(a.s, b.s)<0;
		return strcmp(a.s, b.s)<=0; //发现写成这样就可以当做multi_map来用了。。。神奇。。。见输出对比。。。
	}
};
map<node1, int, cmp> a;
map<node1, int, cmp>::iterator it;

int main()
{
	int i, j, t, cnt=0;
	freopen("1.in", "r", stdin);
	while(gets(b.s))
	{
		a[b]++;
		cnt++;
	}
	for(it=a.begin(); it!=a.end(); it++)
	{
		printf("%s %.4lf\n", (*it).first.s, (double)(*it).second/cnt*100);
	}

	return 0;
}
/*
正解:
Ash 44.4444
Cherry 22.2222
Cottonwood 11.1111
Red Alder 11.1111
Willow 11.1111

用<=时结果。。
Ash 11.1111
Ash 11.1111
Ash 11.1111
Ash 11.1111
Cherry 11.1111
Cherry 11.1111
Cottonwood 11.1111
Red Alder 11.1111
Willow 11.1111
*/


 

发布了68 篇原创文章 · 获赞 23 · 访问量 22万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章