您的位置:首页 > 其它

九度 oj 题目1446:Head of a Gang

2017-01-13 16:58 411 查看
http://ac.jobdu.com/problem.php?pid=1446

并查集 && 双向hash

部分参考了 http://blog.csdn.net/jdplus/article/details/19759729
#include <stdio.h>
#include <cstring>
#include <algorithm>

typedef struct gang{
char head[4];
int members;
friend bool operator < (struct gang a, struct gang b){
return strcmp(a.head,b.head) <0;
}
} Gang;

static Gang gangs[2010];
static int Name2Num[30*30*30];
static int Num2Name[2010];
static int folk[2010];
static int timesPeople[2010];

int NameHash(char name[]){
int hashcode = 0;
for (int i = 0; i < 3; ++i) {
hashcode*=26;
hashcode += name[i]-'A';
}
return hashcode;
}

void NumHash(int code, char name[]){
for (int i = 2; i >=0 ; --i) {
name[i] = (code%26 + 'A');
code /=26;
}
name[3] = '\0';
}

int find(int u){
return u == folk[u] ? u: folk[u] = find(folk[u]);
}

int main(){
//freopen("in/1446.in","r",stdin);
int n,k;
while(scanf("%d %d",&n,&k)!=EOF ){
memset(Name2Num,-1,sizeof(Name2Num));
int nPeople = 0,times;
char name1[4],name2[4];

for (int i = 0; i < 2010; ++i){
folk[i] = i;
timesPeople[i] = 0;
}

for (int i = 0; i < n; ++i) {
scanf("%s %s %d",name1,name2,×);
int namecode1 = NameHash(name1);
int namecode2 = NameHash(name2);
if(Name2Num[namecode1] == -1){
Name2Num[namecode1] = nPeople;
Num2Name[nPeople++] = namecode1;
}
if(Name2Num[namecode2] == -1){
Name2Num[namecode2] = nPeople;
Num2Name[nPeople++] = namecode2;
}
int idx1 = Name2Num[namecode1], idx2 = Name2Num[namecode2];
timesPeople[idx1] += times, timesPeople[idx2] += times;
if(find(idx1) != find(idx2) ) folk[find(idx2)] = find(idx1);
}

//Important: to find the topest folk;
for (int i = 0; i < nPeople; ++i) find(i);

int nGang = 0;
for (int i = 0; i < nPeople; ++i) {
if(folk[i] == i){
int head = i, maxTimes = -1, members = 0 , weight = 0;
//find members
for (int j = 0; j < nPeople; j++) {
if(folk[j] == i){
members ++;
weight += timesPeople[j];
if(timesPeople[j] > maxTimes) {
head = j, maxTimes = timesPeople[j];
}
}
}
if(members > 2 && (weight>>1) > k){
char headName[4];
NumHash(Num2Name[head],headName);
strcpy(gangs[nGang].head, headName);
gangs[nGang++].members = members;
}
}
}
std::sort(gangs,gangs+nGang);
printf("%d\n",nGang);
for (int i = 0; i < nGang; ++i) {
printf("%s %d\n",gangs[i].head,gangs[i].members);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  oj 九度 并查集