题目:
团队链接:button
题面:
有
n
n
n个开关,一开始都处于开状态,已知某些开关按下时会让其他一些已经闭合的按钮弹开,问是否能让所有开关闭合,
如果能,求最少步数及字典序最小的方案,否则输出"no solution"
范围:
n
<
=
30000
n<=30000
n<=30000,关系总数
m
<
=
1
0
7
m<=10^7
m<=107
样例1:
输入:
6
2 2 3
0
2 4 5
0
0
0
输出:
6
1 2 3 4 5 6
样例2:
输入:
4
1 2
1 3
1 1
1 4
输出:
no solution
题解:
这个题,,当时没有一眼看出来是拓扑排序,,,当时可能傻掉了,,这是拓扑排序判环,相当于板子题了吧,,(还是好好写题解吧,,)
如果按下x会让y弹起来的话,那就x必须在y之前被按下,所以很显然就想到和度有关系,那么就是拓扑排序了,其中如果有环的话就是无解了,否则最少的步数一定是n。
由于要字典序最小的,那就不能把入度为0的点放在队列中,你开个优先队列就行了。
代码:
#include<bits/stdc++.h>
using namespace std;
inline int read()
{
int s=0,w=1; char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch<='9'&&ch>='0')s=s*10+ch-'0',ch=getchar();
return s*w;
}
const int sea=1e7+7;
const int pool=3e4+7;
priority_queue<int,vector<int>,greater<int> >Q;
struct see{int x,ver,next,edge;}e[sea<<1];
int n,tot,cnt,ans[pool],d[pool],last[sea<<1];
void add(int x,int y){++d[y];e[++tot].ver=y;e[tot].x=x;e[tot].next=last[x];last[x]=tot;}
int main()
{
n=read();
for(int i=1;i<=n;i++)
{
int x=read();
for(int j=1;j<=x;j++){int y=read(); add(i,y);}
}
for(int i=1;i<=n;i++) if(!d[i]) Q.push(i);
while(!Q.empty())
{
int x=Q.top(); Q.pop();
ans[++cnt]=x;
for(int i=last[x];i;i=e[i].next)
{
int y=e[i].ver;
if(!--d[y]) Q.push(y);
}
}//拓扑判环即可
if(cnt<n){puts("no solution");return 0;}
printf("%d\n",n);
for(int i=1;i<=n;i++) printf("%d ",ans[i]);
return 0;
}