Highest Price in Supply Chain (DFS和BFS)

1090 Highest Price in Supply Chain

原題鏈接

PAT 甲級 1090

解題思路

這道題是求最深的葉子結點的個數以及其深度。
那麼就遍歷整棵樹,發現訪問到葉子結點時就更新全局的最大深度和結點個數。

源代碼

DFS

深度搜索的函數參數需要的參數是當前訪問的結點下標序號index和當前結點的深度depth;

#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
const int maxn = 100010;
struct node
{
    vector<int> child;
}tree[maxn];
int maxDepth = 0;//最大深度
int num = 0;//最大深度的結點個數
void DFS(int index,int depth)//index爲當前訪問的結點編號,depth爲當前深度
{
    if(tree[index].child.size() == 0)//到達葉子節點
    {
        if(depth > maxDepth)
        {
            maxDepth = depth;
            num=1;
        }
        else if(depth == maxDepth)
            num++;
        return ;
    }
    for(int i=0; i<tree[index].child.size(); i++)
    {
        DFS(tree[index].child[i],depth+1);
    }
}
int n;
double p,r;
int main(){
    int root;
    int father;
    scanf("%d%lf%lf",&n,&p,&r);
    r/=100;//不要忘記
    for(int i=0; i<n; i++){
        scanf("%d",&father);
        if(father==-1)
            root=i;//想清楚了這裏
        else
            tree[father].child.push_back(i);//這句是最最關鍵的,不要搞反了
    }
    DFS(root,0);
    printf("%.2f %d",p*pow(1+r,maxDepth),num);
    return 0;
}

BFS

這個用優先隊列實現,結點深度放在結點結構體中當成員變量。
其實就是樹的層序遍歷。

#include<iostream>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
const int maxn=100010;
struct node{
    vector<int> child;
    int depth;
}tree[maxn];
int maxDepth=0;//最大深度
int num=0;//最大深度的結點個數
int n;
double p,r;
void BFS(int root){
	queue<int> q;
	q.push(root);
	while(!q.empty()){
		int top = q.front();
		q.pop();
		//如果是葉子結點
		if(tree[top].child.size() == 0){
			if(tree[top].depth > maxDepth){
				maxDepth = tree[top].depth;
				num = 1;
			}
			else if(tree[top].depth == maxDepth)
				num++;
		} 
		for(int i=0; i<tree[top].child.size(); i++){
			int child = tree[top].child[i];
			tree[child].depth = tree[top].depth+1;
			q.push(child);
		}
	}
} 
int main(){
    int root;
    int father;
    scanf("%d%lf%lf",&n,&p,&r);
    r/=100;
    for(int i=0; i<n; i++){
        scanf("%d",&father);
        if(father==-1)
            root=i;//說明根結點爲i號 
        else
            tree[father].child.push_back(i);//這句是最最關鍵的,不要搞反了
    }
    tree[root].depth = 0;//根結點深度設爲1 
    BFS(root);
    printf("%.2f %d",p*pow(1+r,maxDepth),num);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章