您的位置:首页 > 其它

【codevs 2833】奇怪的梦境

2017-09-02 21:46 435 查看
题目描述 Description

Aiden陷入了一个奇怪的梦境:他被困在一个小房子中,墙上有很多按钮,还有一个屏幕,上面显示了一些信息。屏幕上说,要将所有按钮都按下才能出去,而又给出了一些信息,说明了某个按钮只能在另一个按钮按下之后才能按下,而没有被提及的按钮则可以在任何时候按下。可是Aiden发现屏幕上所给信息似乎有矛盾,请你来帮忙判断。

输入描述 Input Description

第一行,两个数N,M,表示有编号为1…N这N个按钮,屏幕上有M条信息。

接下来的M行,每行两个数ai,bi,表示bi按钮要在ai之后按下。所给信息可能有重复,保证ai≠bi。

输出描述 Output Description

若按钮能全部按下,则输出“o(∩_∩)o”。

若不能,第一行输出“T_T”,第二行输出因信息有矛盾而无法确认按下顺序的按钮的个数。输出不包括引号。

样例输入 Sample Input

3 3

1 2

2 3

3 2

样例输出 Sample Output

T_T

2

数据范围及提示 Data Size & Hint

对于30%的数据,保证0<N≤100。

对于50%的数据,保证0<N≤2000。

对于70%的数据,保证0<N≤5000。

对于100%的数据,保证0<N≤10000,0

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=10000+2;
int l[maxn];//入度
bool b[maxn][maxn];
int s=0;
void topsort(int n)
{
int k=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(l[j]==0)
{
l[j]--;
k=j;
s++;
break;
}
}
for(int j=1;j<=n;j++)
{
if(b[k][j]==true)
{
b[k][j]=false;
l[j]--;
}
}
}
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
int u,v;
memset(l,0,sizeof(l));
memset(b,0,sizeof(b));
while(m--)
{
scanf("%d%d",&u,&v);
if(b[u][v]==false)
{
b[u][v]=true;
l[v]++;
}
}
topsort(n);
if(s<n) cout<<"T_T"<<endl<<n-s<<endl;
else cout<<"o(¡É_¡É)o"<<endl;
return 0;
}


邻接表+优先队列

注意数组大小!

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=25000+5;
int first[maxn],nxt[maxn],tot;
int ru[maxn];
int n,m;
int s=0;//弹出的点的数量
void init()
{
memset(first,0xfff,sizeof(first));
tot=0;
return;
}
struct edge
{
int f,t;
}l[maxn];
void build(int f,int t)
{
l[++tot]=(edge){f,t};
nxt[tot]=first[f];
first[f]=tot;
return;
}
void top_sort(int n)
{
priority_queue<int,vector<int>,greater<int> >q;//优先队列  注意加空格
for(int i=1;i<=n;i++)
{
if(ru[i]==0)
{
q.push(i);//把入度为0的点放在队列中
ru[i]--;
}
}
while(!q.empty())
{
int u=q.top();
q.pop();
s++;
for(int i=first[u];i!=-1;i=nxt[i])//i!=-1的条件好好写别偷懒否则会错!
{
ru[l[i].t]--;
if(ru[l[i].t]==0)
q.push(l[i].t);
}
}
return;
}
int main()
{
scanf("%d%d",&n,&m);
memset(ru,0,sizeof(ru));
init();
int f,t;
for(int i=1;i<=m;i++)
{
scanf("%d%d",&f,&t);
build(f,t);
ru[t]++;
}
top_sort(n);
if(s<n) cout<<"T_T"<<'\n'<<n-s<<'\n';
else cout<<"o(?é_?é)o"<<'\n';
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: