Codeforces Round #647 (Div. 2) - Thanks, Algo Muse! 参与排名人数12044
[codeforces 1362D] Johnny and Contribution 验证拓扑排序
总目录详见https://blog.csdn.net/mrcrack/article/details/103564004
在线测评地址https://codeforces.com/contest/1362/problem/D
Problem | Lang | Verdict | Time | Memory |
---|---|---|---|---|
D - Johnny and Contribution | GNU C++17 | Accepted | 405 ms | 15900 KB |
The last line contains n integers t1,t2,…,tn, i-th of them denotes desired topic number of the i-th blog (1≤ti≤n).
Otherwise, output n distinct integers p1,p2,…,pn (1≤pi≤n), which describe the numbers of blogs in order which Johnny should write them.
这两句比较难理解,通过样例来说明
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
位置1 2 3 4 5
数值2 1 2 2 1
博客1对应话题2
博客2对应话题1
博客3对应话题2
博客4对应话题2
博客5对应话题1
Output
2 5 1 3 4
位置1 2 3 4 5
数值2 5 1 3 4
第1步写博客2
第2步写博客5
第3步写博客1
第4步写博客3
第5步写博客4
在样例的模拟过程中,发现了并查集,拓扑排序的影子,但又不同。进一步的模拟,发现该题目的在于:验证拓扑排序的正确与否。
样例数据对应拓扑排序如下
Input:
3 3
1 2
2 3
3 1
2 1 3
Output:
2 1 3
下图很明显,不是拓扑排序,画不出箭头
Input:
3 3
1 2
2 3
3 1
1 1 1
Output:
-1
Input:
5 3
1 2
2 3
4 5
2 1 2 2 1
Output:
2 5 1 3 4
AC代码如下
#include <cstdio>
#include <algorithm>
#define maxn 500010
using namespace std;
int n,m,a[maxn],b[maxn],fa[maxn],tot,head[maxn];
struct node{
int to,next;
}e[maxn<<1];
int cmp(int x,int y){//注意x,y是数组a[]的脚标
return a[x]<a[y];
}
void add_edge(int u,int v){//邻接表
tot++,e[tot].to=v,e[tot].next=head[u],head[u]=tot;
}
void init(){
int i,u,v;
scanf("%d%d",&n,&m);
for(i=1;i<=m;i++){
scanf("%d%d",&u,&v);
add_edge(u,v),add_edge(v,u);//无向图
}
for(i=1;i<=n;i++)b[i]=i,scanf("%d",&a[i]);
}
void solve(){
int i,c,v;
sort(b+1,b+1+n,cmp);//b[]用来记录a[]的脚标
for(i=1;i<=n;i++){//验证拓扑排序
if(fa[b[i]]+1!=a[b[i]]){printf("-1\n");return;}//找不到匹配的父子关系
for(c=head[b[i]];c;c=e[c].next){//当前的节点b[i]作为爸爸,找寻父子关系.
v=e[c].to;//v表示子节点
if(fa[v]+1==a[b[i]])fa[v]=a[b[i]];//建立拓扑排序(一个孩子可以有多个爸爸;一个爸爸可以有多个孩子)
}
}
for(i=1;i<=n;i++)printf("%d ",b[i]);//验证成功,打印拓扑排序
printf("\n");
}
int main(){
init();
solve();
return 0;
}