1. 程式人生 > >PTAL2-007 家庭房產解題報告---DFS遍歷(鄰接表vector實現)

PTAL2-007 家庭房產解題報告---DFS遍歷(鄰接表vector實現)

                                     L2-007 家庭房產 (25 分)

給定每個人的家庭成員和其自己名下的房產,請你統計出每個家庭的人口數、人均房產面積及房產套數。

輸入格式:

輸入第一行給出一個正整數N(≤1000),隨後N行,每行按下列格式給出一個人的房產:

編號 父 母 k 孩子1 ... 孩子k 房產套數 總面積

其中編號是每個人獨有的一個4位數的編號;

分別是該編號對應的這個人的父母的編號(如果已經過世,則顯示-1);k(0≤k≤5)是該人的子女的個數;孩子i是其子女的編號。

輸出格式:

首先在第一行輸出家庭個數(所有有親屬關係的人都屬於同一個家庭)。隨後按下列格式輸出每個家庭的資訊:

家庭成員的最小編號 家庭人口數 人均房產套數 人均房產面積

其中人均值要求保留小數點後3位。家庭資訊首先按人均面積降序輸出,若有並列,則按成員編號的升序輸出。

輸入樣例:

10
6666 5551 5552 1 7777 1 100
1234 5678 9012 1 0002 2 300
8888 -1 -1 0 1 1000
2468 0001 0004 1 2222 1 500
7777 6666 -1 0 2 300
3721 -1 -1 1 2333 2 150
9012 -1 -1 3 1236 1235 1234 1 100
1235 5678 9012 0 1 50
2222 1236 2468 2 6661 6662 1 300
2333 -1 3721 3 6661 6662 6663 1 100

輸出樣例:

3
8888 1 1.000 1000.000
0001 15 0.600 100.000
5551 4 0.750 100.000

鄰接表的使用,實現關聯成員搜尋

AC Code: 

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<string>
#include<cctype>
#include<map>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<set>
#define INF 0x3f3f3f3f
using namespace std;
static const int MAX_N = 1e5;
typedef long long ll;
struct Node{	//最小編號、成員數、人均房產、人均地產
	int minl;
	int num;
	double house;
	double area;
}info[MAX_N];
struct Node res[MAX_N];
int cnt;	//家庭數
vector<int> V[MAX_N];	//鄰接表儲存關聯節點
bool vis[MAX_N], used[MAX_N];
bool cmp(const Node &a, const Node &b) {	//優先順序排序
	return a.area > b.area || (a.area == b.area && a.minl < b.minl);
}
void dfs(int s) {	//搜尋關聯節點
	vis[s] = true;
	res[cnt].minl = min(s, res[cnt].minl);
	res[cnt].num++;
	res[cnt].house += info[s].house;
	res[cnt].area += info[s].area;
	for (int i = 0; i < V[s].size(); i++) {
		if (!vis[V[s][i]]) dfs(V[s][i]);
	}
}
int main() {
	int n;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		int vnum, vfa, vmo, vk;
		scanf("%d%d%d%d", &vnum, &vfa, &vmo, &vk);
		used[vnum] = true;
		if (vfa != -1) { V[vnum].push_back(vfa); V[vfa].push_back(vnum); }
		if (vmo != -1) { V[vnum].push_back(vmo); V[vmo].push_back(vnum); }
		for (int j = 0; j < vk; j++) {
			int vch;
			scanf("%d", &vch);
			V[vnum].push_back(vch);
			V[vch].push_back(vnum);
		}
		scanf("%lf%lf", &info[vnum].house, &info[vnum].area);
	}
	cnt = 0;
	for (int i = 0; i < 10000; i++) {
		if (used[i]) {
			if (!vis[i]) {
				res[cnt].minl = MAX_N;
				res[cnt].num = res[cnt].house = res[cnt].area = 0;
				dfs(i);
				res[cnt].house /= res[cnt].num;
				res[cnt].area /= res[cnt].num;
				cnt++;
			}
		}
	}
	sort(res, res + cnt, cmp);
	printf("%d\n", cnt);
	for (int i = 0; i < cnt; i++) {
		printf("%04d %d %.3f %.3f\n", res[i].minl, res[i].num, res[i].house, res[i].area);
	}
	return 0;
}