hdu Disjoint-set problems
Disjoint-set namely Union-Find set!
hdu 3172 virtual friends http://acm.hdu.edu.cn/showproblem.php?pid=3172
Yes! A very interesting problem!
Whenever a friendship is formed,printf the number of the peoplein the social network.
OK, I failed lots of time. And all are "Time Limit Exceeded".
But to my surprise! I just replace the "cin" with “scanf” ,"cout" with "printf" in the code,and accepted!
learned: scanf/printf is more efficient than cin/cout;

1 #include<iostream> 2 #include<cstring> 3 #include<string> 4 #include<map> 5 #include<cstdio> 6 using namespace std; 7 int f[200005],num[200005]; 8 void sequence() 9 { 10 int i; 11 for(i=1;i<200005;i++) 12 { 13 f[i]=i; 14 num[i]=1; 15 } 16 } 17 int find(int x) 18 { 19 if(x!=f[x]) 20 f[x]=find(f[x]); 21 return f[x]; 22 23 } 24 void Union(int x,int y) 25 { 26 x=find(x); 27 y=find(y); 28 if(x==y) 29 { 30 printf("%d\n",num[x]); 31 } 32 else 33 { 34 f[y]=x; 35 num[x]+=num[y]; 36 printf("%d\n",num[x]); 37 } 38 } 39 int main() 40 { 41 int t; 42 map<string,int>match; 43 while(scanf("%d",&t)!=EOF) 44 { 45 int k; 46 string name1,name2; 47 while(t--) 48 { 49 sequence(); 50 match.clear(); 51 scanf("%d",&k); 52 int s=1; 53 while(k--) 54 { 55 cin>>name1>>name2; 56 if(match.find(name1)==match.end()) 57 { 58 s++;match[name1]=s; 59 } 60 if(match.find(name2)==match.end()) 61 { 62 s++;match[name2]=s; 63 } 64 Union(match[name1],match[name2]); 65 } 66 } 67 } 68 return 0; 69 } 70 71 72 73 74
Post by heat_nan @2013-03-17 12:03
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?