POJ 3660(dfs)

题目

N (1 ≤ N ≤ 100) cows, conveniently numbered 1…N, are participating in a programming contest. As we all know, some cows code better than others. Each cow has a certain constant skill rating that is unique among the competitors.
The contest is conducted in several head-to-head rounds, each between two cows. If cow A has a greater skill level than cow B (1 ≤ A ≤ N; 1 ≤ B ≤ N; A ≠ B), then cow A will always beat cow B.
Farmer John is trying to rank the cows by skill level. Given a list the results of M (1 ≤ M ≤ 4,500) two-cow rounds, determine the number of cows whose ranks can be precisely determined from the results. It is guaranteed that the results of the rounds will not be contradictory.

题解

1. dfs

第一个想到的方法,就是只要一个节点的入度加上出度 等于 n-1,就说明他的位置可以确定,刚开始我一直在想一种可以一遍dfs就能将所有dfs解出来的方法可是不行,走进了死胡同里,后来看到别人的代码才恍然大悟,数据规模不大,其实可以对每个点都进行dfs,不用强求一遍完成

#include<bits/stdc++.h>
using namespace std;
const int MAXM=5000;
const int MAXN=1000;
struct
{
	int v,nxt;
}edge[2][MAXM];
int head[2][MAXN],cnt[2],vis[2][MAXN],ans[2];
void add_edge(int u,int v,int i) //链式前向星
{
	edge[i][++cnt[i]].v=v;
	edge[i][cnt[i]].nxt=head[i][u];
	head[i][u]=cnt[i];
}
void dfs(int x,int m)
{
	for(int i=head[m][x];i;i=edge[m][i].nxt){
		int v=edge[m][i].v;
		if(!vis[m][v]){
			ans[m]++;
			vis[m][v]=1;
			dfs(v,m);
		}
	}
}
int main()
{
	int n,m,m1,m2;
	cin>>n>>m;
	for(int i=1;i<=m;i++){
		scanf("%d%d",&m1,&m2);
		add_edge(m1,m2,0);
		add_edge(m2,m1,1);
	}
	int t=0;
	for(int i=1;i<=n;i++){
		memset(vis,0,sizeof(vis));
		ans[0]=0;ans[1]=0;
		dfs(i,0);
		dfs(i,1);
		if(ans[0]+ans[1]==n-1) t++;
	}
	cout<<t<<endl;
}

并查集+拓扑

如果有一个节点可以判断他的排名,那么图一定是联通图,所以先用并查集判断联通块的数量,只要大于1,答案就是0。然后拓扑排序的部分,需要一点思维难度,首先进行入队出队操作时,可以确定排名的点肯定会有唯一一个存在队伍中的情况,而且只要他唯一一个存在于队伍中,说明后面的点都与他相连,接着就是判断前面的点是否与这个点相连,更新方式是如果s->j,那么path[ j ][ a[i] ] = path[ s ][ a[i] ],代码网上有很多就不写了

FLoyd

最无脑简单暴力的方式

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值