九度 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
并查集 && 双向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; }
相关文章推荐
- 九度1526
- 一些OJ网站
- 【OJ日志】超级约瑟夫
- 【OJ日志】爬楼梯
- 【OJ日志】删除升序数组的重复数字
- 几个比较大的在线提交系统(Online Judge)
- 杭电 1272 poj 1308 小希的迷宫
- 杭电bfs 水题1241 Oil Deposits - 油田 详解 + 分析
- Max Sum 杭电 1003
- The Blocks Problem
- 初学ACM - 半数集(Half Set)问题 NOJ 1010 / FOJ 1207
- 1611:The Suspects
- 求集合的交并补集
- LeetCode-Rotate Array
- LeetCode-Sudoku Solver
- LeetCode-Minimum Window Substring
- 作业四,1001
- 作业四1002
- 作业四1003
- 练习四1005