POJ 1988 Cube Stacking
2016-07-23 17:21
316 查看
题目地址
total[x]记录最下方木块是x,这一堆总共有多少木块
under[x]记录x木块下面有几块木块
#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<cctype>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=30000 + 5;
int Par[maxn],total[maxn],under[maxn];
int getPar(int x){
if(Par[x]==x) return x;
int p=getPar(Par[x]);
under[x]+=under[Par[x]]; //加上到那一堆之前的所有根节点
Par[x]=p;
return p;
}
void merge(int a,int b){
int p1=getPar(a);
int p2=getPar(b);
if(p1==p2) return ;
Par[p2]=p1;
under[p2]=total[p1];
total[p1]+=total[p2];
}
int main()
{
int N;
cin>>N;
for(int i=1;i<maxn;i++){
total[i]=1;
under[i]=0;
Par[i]=i;
}
string cmd;
while(N--)
{
cin>>cmd;
if(cmd[0]=='M') {
int x,y; cin>>x>>y;
merge(y,x);
}
else {
int x; cin>>x;
getPar(x);
cout<<under[x]<<endl;
}
}
return 0;
}
total[x]记录最下方木块是x,这一堆总共有多少木块
under[x]记录x木块下面有几块木块
#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<cctype>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=30000 + 5;
int Par[maxn],total[maxn],under[maxn];
int getPar(int x){
if(Par[x]==x) return x;
int p=getPar(Par[x]);
under[x]+=under[Par[x]]; //加上到那一堆之前的所有根节点
Par[x]=p;
return p;
}
void merge(int a,int b){
int p1=getPar(a);
int p2=getPar(b);
if(p1==p2) return ;
Par[p2]=p1;
under[p2]=total[p1];
total[p1]+=total[p2];
}
int main()
{
int N;
cin>>N;
for(int i=1;i<maxn;i++){
total[i]=1;
under[i]=0;
Par[i]=i;
}
string cmd;
while(N--)
{
cin>>cmd;
if(cmd[0]=='M') {
int x,y; cin>>x>>y;
merge(y,x);
}
else {
int x; cin>>x;
getPar(x);
cout<<under[x]<<endl;
}
}
return 0;
}
相关文章推荐
- Java 抽象类 接口 继承 实现
- Android常用开发工具类
- 针对PagerSlidingTabStrip 1.3的功能改善(滑动条长度根据标题长度动态变化)
- template model
- Java进阶(三十七)java 自动装箱与拆箱
- iOS应用文件夹
- 字节序不是由操作系统决定的,而是由cpu架构决定的
- java中序列化之子类继承父类序列化
- 【HDU】2588 - GCD(欧拉函数)
- [gdc16]《星球大战:前线》的美术制作技术
- 2016夏季练习——最小生成树
- poll 机制
- 摘自:javascript的理解DOM事件流的三个阶段
- error: 'retain' is unavailable: not available in automatic reference counting
- 字符串匹配优化(KMP)(写+转载)
- Managing Processes and Threads in Windows Forms
- PHP导出word文档的简单实现方法(可导出图片)
- poj 3641 Pseudoprime numbers
- [干货] Flume综述与实例
- 2012杭州赛区(浙江理工大学)J - Scaring the Birds