Topological sorting review notes

I suddenly thought of topological sorting when I was lifting iron in the gym today. Today I will make a review note.


Title introduction

HDU-1285
确定比赛名次
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 55040 Accepted Submission(s): 20319

Problem Description
There are N competition teams (1<=N<=500), and the numbers are 1, 2, 3, in order. . . . , N plays the game. After the game, the referee committee will rank all participating teams from front to back, but now the referee committee cannot directly obtain the results of each team. It only knows the result of each game, that is, P1 wins P2. P1 and P2 indicate that P1 is before P2 in ranking. Now please program you to determine the ranking.


There are several groups of Input . The first line in each group is two numbers N (1<=N<=500), M; where N represents the number of teams, and M represents the next M lines of input data. In the next M rows of data, each row also has two integers P1, P2 means that the P1 team won the P2 team.

Output
gives a ranking that meets the requirements. When outputting, there are spaces between the team numbers, and there is no space after the last one.

Other explanations: The qualified ranking may not be unique. At this time, the team with the lower number is required to be the first when outputting; the input data is guaranteed to be correct, that is, the input data must be guaranteed to have a ranking that meets the requirements.

Sample Input
4 3
1 2
2 3
4 3

Sample Output
1 2 4 3


1. What is the topology?

The definition of topological sorting Topological sorting of
a Directed Acyclic Graph (DAG) G is to arrange all vertices in G into a linear sequence, so that any pair of vertices u and v in the graph, if edge <u ,v>∈E(G), then u appears before v in the linear sequence. Generally, such a linear sequence is called a sequence that satisfies the topological order (Topological Order), referred to as a topological sequence. Simply put, from a partial order on a set to get a total order on the set, this operation is called topological sorting.

Second, the execution steps

Insert picture description here

The topological sorting algorithm mainly executes the following two steps in a loop until there are no vertices with an in-degree of 0.
(1) Select the node with 0 in degree and output it;
(2) Delete this node and all outgoing edges from the network;

After the cycle is over, if the number of output nodes is less than the number of nodes in the network, the output "has loop" information, otherwise the output node sequence is a topological sequence. [2]


Three, AC code

#include<bits/stdc++.h>
using namespace std;
int n,m;
int mp[550][550];
int ans[550],in[550];
void tp(){
    
    
    //寻找有点指向的点,并进行存储
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            if(mp[i][j])in[j]++;
    
    for(int i=1;i<=n;i++){
    
    
        int temp = 1;
        while(in[temp]!=0)temp++;
        ans[i] = temp;
        in[temp] = -1;
        //切除和temp有关的所有点
        for(int j=1;j<=n;j++)
            if(mp[temp][j])in[j]--;
    }
}
int main(){
    
     
 while(~scanf("%d%d",&n,&m)){
    
    
        memset(in, 0, sizeof in);
        //ans数组用来存储排序后的结果
        memset(ans, 0, sizeof ans);
        memset(mp, 0, sizeof mp);
        int x,y;
        for(int i=0;i<m;i++){
    
    
            cin >> x >> y;
            mp[x][y] = 1;
        }
        tp();
        
        for(int i=1;i<=n;i++){
    
    
            cout << ans[i];
            if(i!=n)cout << " ";
            else cout << endl;
        }
    }
    return 0;
    }


Four, algorithm demonstration

Insert picture description here
We can notice that the topological sorting algorithm first finds a node with an in-degree of 0 in the graph (what is an in-degree of 0? You can understand it as a node without an arrow pointing to it), here we find the first one It is a, then delete this vertex and all outgoing edges from the network, it becomes a b graph, and output a at the same time, so that the topological sort can be output by analogy


Expansion questions

There is a similar problem on ZCMU OJ, but some changes need to be made.
ZCMU-2103
2103: The problem of queuing soldiers
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 103 Solved: 33
[Submit][Status][Web Board]
Description
有 N Soldiers (1≤N≤26), numbered in sequence A, B, C,..., during queue training, the commander has to line up some soldiers from high to short at a time, but now the commander cannot directly obtain everyone’s For height information, only comparison results such as "P1 is higher than P2" can be obtained (P1, P2 ∈ A, B, C,..., Z, denoted as P1>P2). For example, "A>B" means that A is higher than B.
Please compile a program to find a queuing scheme with the smallest lexicographic order based on the comparison results obtained.
(Note: Soldiers not involved in the comparison result will not participate in the queue)

Input
comparison result is read in from a text file (the file is input by keyboard), and each comparison result occupies a line in the text file.

Output
If the input data has no solution, print the "No Answer!" message, otherwise output the number of each soldier from high to low without a separator in the middle, and write the result into a text file. The file is input by keyboard:

Sample Input

A>B
B>D
F>D

Sample Output

ABFD

AC code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int mp[50][50],ans[50],in[50];
int cnt,mx = -1;
set<int>s;
void tp(){
    
    
    for(int i=1;i<=mx;i++)
        for(int j=1;j<=mx;j++)
            if(mp[i][j])in[j]++;

   // for(int i=1;i<=mx;i++) cout <<  " "<< in[i];
   //cout << endl;

    for(int i=1;i<=cnt;i++)
    {
    
    
        int temp = 1;
        while(temp<=mx){
    
    
        	这里我们需要确保temp存在于s中
            if((std::find(s.begin(), s.end(), temp) != s.end())&&in[temp]==0)break;
            temp++;
        }
       // cout << "text->" << temp << endl;
        ans[i] = temp;
        in[temp] = -1;

        for(int j=1;j<=mx;j++)
            if(mp[temp][j])in[j]--;
    }
}

int main()
{
    
    
    char a,b,c;
    int x,y,m;
        while(cin>>a>>c>>b) {
    
    
            //cout << a << " " << c <<" " << b << endl;
            x = a - 'A' + 1;
            y = b - 'A' + 1;
            mx = max(mx, x);
            mx = max(mx, y);
            //这里采用了set集合来统计出现多少个不重复的数据
            s.insert(x);
            s.insert(y);
            if (c == '>')mp[x][y] = 1;
            else mp[y][x] = 1;
        }

//    for(set<int>::const_iterator p=s.begin();p!=s.end();++p)
//        cout << *p << " ";
//    cout << endl;

    cnt = s.size();
//    cout << mx << endl;
//    cout << cnt << endl;
    tp();
    for(int i=1;i<=mx;i++) {
    
    
        if (in[i] > 0) {
    
    //若最终还存在入度大于0 的顶点,则无解
            cout << "No Answer!\n";
            return 0;
        }
    }

    for(int i=1;i<=cnt;i++) {
    
    
        if (i != cnt)printf("%c", ans[i]+'A'-1);
        else printf("%c\n",ans[i]+'A'-1);
    }

    return 0;
}

There are several difficulties here. First, the letter data must be converted into numbers, and then the output cannot be output without C and E as in the example. Some small details should be paid attention to.


# Summary of today is to do a review of topological sorting organize notes, later forgets it can come back to go over, but also want to see the students do a help.

Guess you like

Origin blog.csdn.net/DAVID3A/article/details/114328439
Recommended