重量不同的硬币
题目描述
Fj有N个硬币,编号为1…N。
现在有W个推断,为(A,B),表示硬币A比硬币B重。
寻找并输出一个硬币编号,要求其重量明确不同于其他硬币的个数最多。
如果有多个答案,输出字典序最小的一个。
如果给出的数据有矛盾,输出"IMPOSSIBLE"
输入格式
Line 1: 两个整数: N and W.
Lines 2…W+1: 每行两个整数: A, B
输出格式
Line 1: 重量不同于其他硬币的个数最多的硬币编号。
样例数据
input
7 6
1 6
1 5
3 6
4 3
2 4
2 5
output
2
首先,我们知道,如果重量的关系出现了矛盾,一定出现了环,我们可以选择用拓扑排序进行判环:
拓扑排序中的点,要想进入拓扑序列,入度必然为0;但是有环,入度必然不为0.因此,我们统计拓扑排序有多少个点进入拓扑序列,如果有点数sum<n,那么就输出Inpossible。
对于统计大小,我们进行dfs遍历,用cnt[]表示连向这个点的关系,注意每一次的初始化要为1,否则无法进行大小统计。再在反图上做一遍DFS即可。
#include<bits/stdc++.h>
using namespace std;
#define maxn 1200
int n,w;
int ans=0,d=0;
int q[maxn]={
};
int v[maxn]={
};
int V[maxn]={
};
int In[maxn]={
};
int cnt[maxn]={
};
int CNT[maxn]={
};
vector <int> a[maxn];
vector <int> A[maxn];
inline void read(int &readnum)
{
int s=0,w=1;char c=getchar();
while (c<'0' || c>'9') {
if (c=='-') w=-1; c=getchar();}
while (c>='0' && c<='9') s=s*10+c-48,c=getchar();
readnum=s*w;return;
}
inline int Topsort(void)
{
int sum=0;
int h=1,t=0;
for (int i=1;i<=n;++i)
if (!In[i]) q[++t]=i;
for (;h<=t;++h)
{
int p=q[h];sum++;
for (int i=0;i<a[p].size();++i)
{
int np=a[p][i];
In[np]--;
if (!In[np]) q[++t]=np;
}
}
return sum;
}
void dfs(