| "Problem description" |
|
|
There are n soldiers, numbered 1,2,3,..., N, when the queue is trained, the commander will rank some of the soldiers from high to low in turn. But now the commander can not directly obtain everyone's height information, can only get "P1 than P2 High" comparison results: recorded as P1>P2. such as 1>2,2>4,3>4. The height of the soldier is related as shown in the figure:
|
|
|
|
|
"Input Format" |
|
|
First line: contains two integers n, M, second to m+1 line: two integers per line x,y, representing soldier x higher than soldier Y. |
|
|
|
|
"Output Format" |
|
|
A 1. The arrangement of N, which indicates the queue scheme (the minimum Dictionary order) and outputs 1 if there is no feasible solution. |
|
|
|
|
"Input Sample" |
|
|
"Sample 1" 4 3 1 2 2 4 3 4
"Sample 2" 4 4 1 2 2 4 2 3 3 1
|
|
|
|
|
"Output Sample" |
|
|
"Sample 1" 1 2 3 4
"Sample 2" -1
|
|
|
|
|
"Data Range" |
|
|
1<=n<10000 1<=m<=100000 |
Thinking Analysis:
Obviously this question about Dag graph and topological ordering, adopt topological sort algorithm, that is, starting from the entry degree of 0 points, the precedence queue is used because of the request dictionary order. BFS
Code:
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
#define MAXN 10005
using namespace Std;
int n,m,rd[maxn]={0};
vector<int>g[maxn],topo;
struct mycmp{
BOOL operator () (int a,int b) {
Return a>b;
}
};
void Init () {
int x,y;
scanf ("%d%d", &n,&m);
memset (rd,0,sizeof (RD));
for (int i=1;i<=m;i++) {
scanf ("%d%d", &x,&y);
G[x].push_back (y);
rd[y]++;
}
}
BOOL BFS () {
priority_queue<int,vector<int>,mycmp>q;
for (int i=1;i<=n;i++) {
if (rd[i]==0) Q.push (i);
}
while (!q.empty ()) {
int J=q.top ();
Q.pop ();
Topo.push_back (j);
for (int i=0;i<q.size (); i++) {
int k=g[j][i];
if (rd[k]>0) rd[k]--;
if (rd[k]==0) Q.push (k);
}
}
Return topo.size () ==n;
}
int main () {
Init ();
BOOL Ok=bfs ();
if (OK) {
for (int i=0;i<n;i++) {
printf ("%d", topo[i]);
}
}
else printf ("-1");
return 0;
}