现在的位置: 首页 > 综合 > 正文

HDU-1272(并查集)

2013年08月24日 ⁄ 综合 ⁄ 共 792字 ⁄ 字号 评论关闭

坑爹的并查集,,,我觉得作对了,,,为什么老是A不了呢???

以后有哪位大神看到了这个代码 还请看看,到底是哪里错了...

伤不起呀..

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#define MAX 111111

using namespace std;

int flag;

int set[111111];

int cm; //记录一共有多少个点 

int cn;  //记录一共有多少个边 

void init()
{
	memset (set, 0 ,sizeof (set));
}

int find(int x )
{
	return set[x] = (set[x] == x? x: find(set[x]));
}

void build(int a, int b )
{
	if (set[a] == 0)
	{
		set[a] = a;
		cm++;
	}
	if (set[b] == 0)
	{
		set[b] = b;
		cm++;
	}	
//	cout << cm << endl;		
	int x = find (a);
	int y = find (b);
	if (x != y)
	{
		set[x] = y;
	}
	else
	{
		flag = 0;
	}
}

int main()
{
	int a,b;
	init();
	cn = 0;
	cm = 0;
	flag = 1;
	while (scanf("%d %d", &a,&b),a != -1 || b != -1)
	{
		cn ++;
		if (a == 0 && b == 0)
		{
//			cout << "final" << endl;
//			cout << "点的个数" << cm << " 边的个数" << cn - 1 << endl;	
			if (flag == 1 && cm == cn)
			{
				printf("Yes\n");
				cn = 0;
				cm = 0;
			}
			else
			{
				printf("No\n");
				flag = 1;
				cn = 0;
				cm = 0;
			}
			init();
		}
		else
		{
			build (a, b);
		}
	}
	return 0;
		
}

抱歉!评论已关闭.