hdu 6109 数据分割(并查集合并)



数据分割

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1031    Accepted Submission(s): 242


Problem Description
小w来到百度之星的赛场上,准备开始实现一个程序自动分析系统。

这个程序接受一些形如 xi=xj  或  xixj  的相等/不等约束条件作为输入,判定是否可以通过给每个 w 赋适当的值,来满足这些条件。

输入包含多组数据。
然而粗心的小w不幸地把每组数据之间的分隔符删掉了。
他只知道每组数据都是不可满足的,且若把每组数据的最后一个约束条件去掉,则该组数据是可满足的。

请帮助他恢复这些分隔符。
 

Input
1 行:一个数字 L ,表示后面输入的总行数。

之后 L 行,每行包含三个整数, i,j,e ,描述一个相等/不等的约束条件,若 e=1 ,则该约束条件为 xi=xj  ,若 e=0 ,则该约束条件为  xixj  。

i,j,L100000

xi,xjL
 

Output
输出共 T+1 行。

第一行一个整数 T ,表示数据组数。

接下来 T 行的第 i 行,一个整数,表示第i组数据中的约束条件个数。
 

Sample Input
      
      
6 2 2 1 2 2 1 1 1 1 3 1 1 1 3 1 1 3 0
 

Sample Output
      
      
1 6

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
#include<map>
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
typedef long long LL;
const LL mod = 1e9+7;
const int inf = 0x3f3f3f3f;
unordered_map<int,int>q;
int f[N];
set<int>dict[N], st;
int get(int x)
{
    if(f[x]==x) return x;
    f[x]=get(f[x]);
    return f[x];
}
int ans[N];
set<int> ::iterator it;

int main()
{
    int n, k=0, cnt=0;
    scanf("%d", &n);
    for(int i=0; i<=100000; i++) f[i]=i;
    for(int i=0; i<n; i++)
    {
        int x, y, p;
        scanf("%d %d %d", &x, &y, &p);
        int t1=get(x), t2=get(y);
        st.insert(x),st.insert(y);
        if(p==1)
        {
            cnt++;
            if(dict[t2].count(t1))
            {
                ans[++k]=cnt;
                cnt=0;
                for(it=st.begin(); it!=st.end(); it++)
                {
                    dict[*it].clear();
                    f[*it]=*it;
                }
            }
            else if(t1!=t2)
            {
                if(dict[t1].size()>dict[t2].size())swap(t1,t2);
                f[t1]=t2;
                for(it=dict[t1].begin(); it!=dict[t1].end(); it++)
                {
                    dict[t2].insert(*it);
                    dict[*it].erase(t1);
                    dict[*it].insert(t2);
                }
            }
        }
        else
        {
            cnt++;
            dict[t1].insert(t2),dict[t2].insert(t1);
            if(t1==t2)
            {
                ans[++k]=cnt;
                cnt=0;
                for(it=st.begin(); it!=st.end(); it++)
                {
                    dict[*it].clear();
                    f[*it]=*it;
                }
            }
        }
    }
    printf("%d\n",k);
    for(int i=1;i<=k;i++) printf("%d\n",ans[i]);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值