cdoj 1150 排名表 拓扑排序
生活随笔
收集整理的這篇文章主要介紹了
cdoj 1150 排名表 拓扑排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
排名表
Time Limit: 20 Sec
Memory Limit: 256 MB
題目連接
http://acm.uestc.edu.cn/#/problem/show/1150
Description
暑假前集訓已經過了一半了,我們將會把當前排名公布出來。但是此刻秋實大哥卻心急火燎,因為他不慎把排名刪除了。一共有n個人參加排名,每個人都有一個名次,沒有哪兩個人的名次是相同的。現在秋實大哥掌握的一些情報,比如Ai的名次要先于Bi。(編號從1開始)
你能幫秋實大哥恢復出排名表嗎?
Input
第一行一個數字 T (T≤10),表示測試數據組數每組測試數據,第一行兩個數 n(1≤n≤200)和 m(0≤m≤40000),接下來m行,每行兩個數a和b(1≤a,b≤N),表示a的名次要先于b
Output
對于每組測試數據,輸出一行,從1號到n號每個人的名次。
如果有多個解,讓編號為1的人的名次盡量小,然后讓編號為2的人的名次盡量小,然后讓編號為3的人的名次盡量小......
如果沒有解,輸出?1
Sample Input
5
4 0
4 1
1 1
4 2
1 2
2 1
4 1
2 1
4 1
3 2
Sample Output
1 2 3 4
-1
-1
2 1 3 4
1 3 2 4
HINT
?
題意
?
題解:
逆向拓撲排序,注意,這個是輸出每個的排名,而不是按著排名順序輸出人
代碼:
?
//qscqesze #include <cstdio> #include <cmath> #include <cstring> #include <ctime> #include <iostream> #include <algorithm> #include <set> #include <vector> #include <sstream> #include <queue> #include <typeinfo> #include <fstream> #include <map> #include <stack> typedef long long ll; using namespace std; //freopen("D.in","r",stdin); //freopen("D.out","w",stdout); #define sspeed ios_base::sync_with_stdio(0);cin.tie(0) #define maxn 200001 #define mod 10007 #define eps 1e-9 int Num; char CH[20]; //const int inf=0x7fffffff; //нчоч╢С const int inf=0x3f3f3f3f; /*inline void P(int x) {Num=0;if(!x){putchar('0');puts("");return;}while(x>0)CH[++Num]=x%10,x/=10;while(Num)putchar(CH[Num--]+48);puts(""); } */ inline ll read() {ll x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f; } inline void P(int x) {Num=0;if(!x){putchar('0');puts("");return;}while(x>0)CH[++Num]=x%10,x/=10;while(Num)putchar(CH[Num--]+48);puts(""); } //**************************************************************************************int head[maxn]; int top; int d[maxn]; priority_queue<int>q; struct edge {int v,next; }e[maxn]; int cnt; int ans[maxn]; int ans1[maxn]; int n,m; void insert(int u,int v) {e[cnt].v=v;e[cnt].next=head[u];head[u]=cnt;cnt++; }void solve(int x) {q.pop();ans[++top]=x;for(int i=head[x];i>=0;i=e[i].next){d[e[i].v]--;if(d[e[i].v]==0)q.push(e[i].v);} }int main() {//freopen("test.txt","r",stdin);int t=read();while(t--){n=read(),m=read();cnt=top=0;memset(head,-1,sizeof(head));memset(d,0,sizeof(d));for(int i=1;i<=m;i++){int u=read(),v=read();insert(v,u);d[u]++;}for(int i=1;i<=n;i++)if(!d[i])q.push(i);while(!q.empty()){solve(q.top());}if(top!=n)printf("-1\n");else{int cnt3=1;int first=1;for(int i=n;i;i--){ans1[ans[i]]=cnt3++;}for(int i=1;i<=n;i++){if(i==1)printf("%d",ans1[i]);elseprintf(" %d",ans1[i]);}printf("\n");}}return 0; }?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的cdoj 1150 排名表 拓扑排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 做梦梦到鬼被吓醒是什么意思
- 下一篇: 孕妇梦到抓螃蟹预示着什么