我看别人代码觉得思路请求, 我就只会用固定的套路和格式。
#include <cstdio>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
struct Node{
int id;
double number,area;
int people;
double avgNum, avgArea;
Node (){
people=1;
}
}node[10010];
bool cmp(int a, int b){
if (node[a].avgArea!=node[b].avgArea) return node[a].avgArea>node[b].avgArea;
else return node[a].id<node[b].id;
}
int father[10010];
int findFather(int x){
int a=x;
while (x!=father[x]){
x=father[x];
}
while (a!=father[a]){
int z=a;
a=father[a];
father[z]=x;
}
return x;
}
void Union(int a, int b){
int faA=findFather(a);
int faB=findFather(b);
if (faA!=faB){
father[faA]=faB;
}
}
void init(){
for (int i=0; i<10010; i++){
father[i]=i;
node[i].id=i;//不是所有人都有房子
}
}
int hashTable[10010]={0};
int n;
int main(){
scanf("%d",&n);
init();//重中之重
for (int i=0; i<n; i++){
int id,fa,mo,childNum;
scanf("%d %d %d %d",&id, &fa, &mo, &childNum);
hashTable[id]++;
if (fa!=-1) {
Union(id,fa);
hashTable[fa]++;
}
if (mo!=-1) {
Union(id,mo);
hashTable[mo]++;
}
for (int j=0; j<childNum; j++){
int temp;
scanf("%d",&temp);
Union(id, temp);
hashTable[temp]++;
}
scanf("%lf %lf",&node[id].number, &node[id].area);
}
vector<int> family;
int haveIn[10010]={0};
for (int i=0; i<10010; i++){
if (hashTable[i]){
int father=findFather(i);
if (!haveIn[father]){
family.push_back(father);
haveIn[father]=1;
}
if (father!=i){//这里很容易错
if (node[father].id>node[i].id){
node[father].id=node[i].id;
}
node[father].area+=node[i].area;
node[father].number+=node[i].number;
node[father].people++;
}
node[father].avgArea=node[father].area/node[father].people;
node[father].avgNum=node[father].number/node[father].people;
}
}
sort(family.begin(), family.end(), cmp);
printf("%d\n",family.size());
for (int i=0; i<family.size(); i++){
int index=family[i];
printf("%04d %d %.3f %.3f\n",node[index].id, node[index].people, node[index].avgNum, node[index].avgArea);
}
}
自己想太麻烦 还是用套路比较好。