Description
挑竹签——小时候的游戏
夏夜,早苗和诹访子在月光下玩起了挑竹签这一经典的游戏。
挑竹签,就是在桌上摆上一把竹签,每次从最上层挑走一根竹签。如果动了其他的竹签,就要换对手来挑。在所有的竹签都被挑走之后,谁挑走的竹签总数多,谁就胜了。
身为神明的诹访子自然会让早苗先手。为了获胜,早苗现在的问题是,在诹访子出手之前最多能挑走多少竹签呢?
为了简化问题,我们假设当且仅当挑最上层的竹签不会动到其他竹签。
Input
输入文件mikado.in。
第一行输入两个整数n,m, 表示竹签的根数和竹签之间相压关系数。
第二行到m+1 行每行两个整数u,v,表示第u 根竹签压住了第v 根竹签。
Output
输出文件mikado.out。
一共一行,一个整数sum,表示最多能拿走sum 根竹签。
Sample Input
6 6
1 2
2 3
3 1
4 3
4 5
6 5
Sample Output
3
样例解释:
一共有6 根竹签,其中1 压住2,2 压住3,3 压住1,4 压住3 和5,6 压住5。最优方案中,我们可以依次挑走4、6、5 三根竹签。而剩下的三根相互压住,都无法挑走。所以最多能挑走3 根竹签。
Data Constraint
对于20% 的数据,有1<= n,m<= 20。
对于40% 的数据,有1 <= n,m <= 1 000。
对于100% 的数据,有1 <= n,m <= 1 000 000。
思路
其实就是一个近乎裸的拓扑排序,本题就是每次找到入度为0的点然后累加答案,并且删掉这个点,这里是把它的指向得点给去掉,广度优先搜索+队列优化。
其实我的程序用快排找入度为0的点是要O(n logn),还不如直接for暴力一遍O(n),更快,而且不用memcpy复制,所以要认真估计好时间复杂度,不然后果可能很严重。
本人的程序用了STL库的队列,就是那个ss,不懂得可以百度一下,不过用STL会方便一些
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#define N 1000009
#define fo(i,a,b) for(int i=a;i!=0;i=b)
#define mem(n) for(int i=1;i<=n;i++)a[w[i].po]=w[i].dis
typedef long L;
typedef long long LL;
using namespace std;
queue <int>ss;
L n,m;
L xx,yy;
struct text{L to,nxt;}p[N];
struct dd{L po,dis;}w[N];
int list[N];
int a[N];
LL ans;
inline bool cmp(dd x,dd y)
{
return x.dis<y.dis;
}
int main()
{
freopen("mikado.in","r",stdin);
freopen("mikado.out","w",stdout);
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
w[i].po=i;
for(int i=1;i<=m;i++)
{
scanf("%d%d",&xx,&yy);
p[i].to=yy;p[i].nxt=list[xx];list[xx]=i;
w[yy].dis++;
}
sort(w+1,w+1+n,cmp);
int i=1;
while(w[i].dis==0)
{
ss.push(w[i].po);
i++;
}
if(ss.empty())
{
printf("0");
return 0;
}
else ans+=i-1;
mem(n);
while(!ss.empty())
{
fo(s,list[ss.front()],p[s].nxt)
{
a[p[s].to]--;
if(!a[p[s].to])
{
ss.push(p[s].to);
ans++;
}
}
ss.pop();
}
printf("%d",ans);
}