1336:【例3-1】找树根和孩子
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m,x,y,root,maxnode,maxn=0,cnt=0;
int tree[105];
memset(tree,0,sizeof(tree));
cin>>n>>m;
for(int i=1;i<=m;i++){
cin>>x>>y;
tree[y]=x;
}
for(int i=1;i<=n;i++){
if(tree[i]==0){
root=i;
break;
}
}
for(int i=1;i<=n;i++){
cnt=0;
for(int j=1;j<=n;j++){
if(tree[j]==i){
cnt++;
}
}
if(cnt>maxn){
maxn=cnt;
maxnode=i;
}
}
cout<<root<<endl<<maxnode<<endl;
for(int i=1;i<=n;i++){
if(tree[i]==maxnode)cout<<i<<" ";
}
return 0;
}
单词查找树
和哈夫曼编码有什么关系呢???
//我也不知道为什么它这样建树就是节点数最少呀!!!
#include<bits/stdc++.h>
using namespace std;
string a[10000];
string s;
int n;
int main(){
while(cin>>a[++n]);
sort(a+1,a+1+n);
int t=a[1].length();
for(int i=2;i<=n;i++){
int j=0;
while(a[i][j]==a[i-1][j]&&j<a[i-1].length()){
j++;
}
t+=a[i].length()-j;
}
cout<<t+1<<endl;
return 0;
}
1338:【例3-3】医院设置
思路:
这是一道简单的二叉树应用问题,问题中的节点数并不多,数据规模也不大,采用邻接矩阵存储,用Floyed求出任意两节点之间的最短路径,然后穷举医院可能建立的n个节点位置找出一个最小距离的位置即可。
其实就是用floyed求一遍多源最短路(任意两点之间的最短路径),然后枚举直接求建立在每一点医院时的耗散值。
学到的东西:
书上说,这类题是树的中心点问题,本来我还想枚举每个点为起点然后用树的遍历来求耗散值呢,看来还是用最短路更简单。
#include<bits/stdc++.h>
#includ