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
*/