1034 forest

大水题,WA到吐了,结果发现犯了一弱智错误,擦

1.定义dept[]数组,主要用bfs ,将子节点的dept值累加父节点的dept值,遍历一颗或者若干树。从根节点(bepointed[]值为false的点)出发遍历全棵树。

2.存储方式:邻接表存边 vector+queue  ,

#include <iostream>
#include<queue>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;

int n,m,a,b;
const int N=102;
bool bepointed[N];
bool circle[N];
int dept[N];
bool flag;
vector<int>vec[N];

bool cmp(const int&a,const int &b)
{
	return a>b;
}

void bfs(int vertex)
{
	queue<int>que1;
	que1.push(vertex);
	while (!que1.empty())
	{
		int a=que1.front();
		circle[a]=true;
		que1.pop();
		for (int i=0;i<vec[a].size();i++)
		{
			int j=vec[a][i];
			if(circle[j]==false)
			{
				dept[j]=dept[a]+1;
				que1.push(j);
			}	
		}
	}	
}

int main()
{
	while(cin>>n>>m&&n!=0)
	{
		flag=0;
		memset(bepointed,false,sizeof(bepointed));
		memset(circle,false,sizeof(circle));
		memset(dept,0,sizeof(dept));
		fill(vec,vec+n+1,vector<int>());
		while (m--)
		{
			cin>>a>>b;
			if(bepointed[b]==true)  	
				flag=1;   //terrible mistake i've made
			bepointed[b]=true;  
			vec[a].push_back(b);
		}
		if(flag)
		{
			cout<<"INVALID"<<endl;
                        continue;
		}
	        int count=0;
		for (int i=1;i<=n;i++)
		{
			if(bepointed[i]==false)
				bfs(i);
			else
				count++;
		}
		if(count==n)
		{
			cout<<"INVALID"<<endl;
			continue;
		}
		int count2=0;
		for (int i=1;i<=n;i++)
			if(circle[i]==true)
				count2++;
		if(count2!=n) //value of count2 stands for the numbers of vertex that has been pushed into the queue.If it does not equal to n, loop exists
		{
			cout<<"INVALID"<<endl;
			continue;
		}
		if(flag) continue;
		int maxx=0;
		for (int i=1;i<=n;i++)
			maxx=max(maxx,dept[i]);
		int wid[102]={0};
		for (int i=1;i<=n;i++)
			wid[dept[i]]++;
		sort(wid,wid+102,cmp);
		cout<<maxx<<" "<<wid[0]<<endl;
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值