算法导论 第22章 22.1-4

#include<iostream>
using namespace std;

typedef struct Gnode
{
	int index;
	struct Gnode *next;
}Gnode;

int N,M;//N表示顶点,M表示边

int main()
{
	scanf("%d %d",&N,&M);
	int i,j;
	bool *visited=new bool[N];
	Gnode *G=new Gnode[N];
	for(i=0;i<N;i++)
	{
		G[i].index=i;
		G[i].next=NULL;
		visited[i]=false;
	}
	int a,b;
	for(i=0;i<M;i++)
	{
		scanf("%d %d",&a,&b);
		if(a==b)
			continue;
		Gnode *temp=&G[a];
		while(temp->next!=NULL)
			temp=temp->next;
		Gnode *temp2=new Gnode;
		temp2->index=b;
		temp2->next=NULL;
		temp->next=temp2;
		temp2=NULL;
		temp2=new Gnode;
		temp2->index=a;
		temp2->next=NULL;
		temp=&G[b];
		while(temp->next!=NULL)
			temp=temp->next;
		temp->next=temp2;
	}
	for(i=0;i<N;i++)
	{
		visited[G[i].index]=true;
		Gnode *temp=&G[i];
		while(temp->next!=NULL)
		{
			Gnode *temp1=temp->next;
			if(visited[temp1->index])
			{
				temp->next=temp1->next;
				free(temp1);
			}
			else
			{
				visited[temp1->index]=true;
				temp=temp1;
			}
		}
		temp=&G[i];
		while(temp!=NULL)
		{
			visited[temp->index]=false;
			temp=temp->next;
		}
	}
	for(i=0;i<N;i++)
	{
		printf("%d",G[i].index);
		Gnode *temp=&G[i];
		while(temp->next!=NULL)
		{
			temp=temp->next;
			printf(" -> %d",temp->index);
		}
		printf(" -> ^\n");
	}
	return 0;
}

测试数据:

4 12
0 0
0 1
0 1
0 1
0 2
1 2
1 2
2 1
2 3
2 3
2 3
3 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值