SDNU1031字母排序(拓撲排序)

第一行——咕咕咕。

第二行感謝csb師哥。

 

先附題目鏈接SDNUOJ1031

這是一道拓撲排序題,不會的指路博客拓撲排序

說一下思路:

1.統計每個字母的入度(按0~25代表A~Z(每次都需要更新

2.當出現環就說明出現了矛盾

3.如果隊列中存在兩個及以上可被取出的字符,即入度爲0有兩個及以上,則爲無法確定全部字母的順序(這句是csb師哥說的

4.如果最後的序列,長度小於n輸出矛盾、

再說一下踩過的坑:

1.復環(這個可能沒問題

2.getchar(這個也可能沒問題

3.局部變量與全局變量(這都能錯

4.輸入明明有可能是'>',我竟然規定了輸入'<'

5.每次輸入都進行拓撲排序不是所有輸入結束進行判斷(這個最重要,我全輸入wa了五次都沒找到鍋在哪兒(再次感謝csb師哥

下附代碼

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <algorithm>
#define ll long long

using namespace std;

string s = "";
int n,m;
int c[27][27];
bool vis[27];
int t[27];

int panduan()
{
    memset(vis,0,sizeof(vis));
    s = "";
    int now[27] = {0};
    for(int i = 0; i < n; ++i)
        now[i] = t[i];
    int q;
    int f = 1;
    for(int i = 0; i < n; ++i)
    {
        int to = 0;
        for(int j = 0; j < n; ++j)
        {
            if(now[j] == 0&&vis[j]==0)
            {
                to++;
                q = j;
            }
        }
        if(to==0)
        {
            return 0;
        }
        if(to>=2)
            f = 2;
        vis[q] = 1;
        for(int j = 0; j < n; ++j)
        {
            if(c[q][j]==1)
            {
                now[j]--;
            }
        }
        s+=q+'A';
    }
    return f;
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        if(n==0&&m==0)
            break;
        char a,b,relation;
        s = "";
        int flag = 0;
        memset(c,0,sizeof(c));
        memset(t,0,sizeof(t));
        int ydr = 0;
        for(int l = 0; l < m; ++l)
        {
            getchar();
            ydr++;
            scanf("%c%c%c",&a,&relation,&b);
            int x = a - 'A';
            int y = b - 'A';
            if(relation == '<')
            {
                if(c[x][y]==0)
                {
                    c[x][y] = 1;
                    t[y]++;
                }
            }
            else if(relation == '>')
            {
                if(c[y][x]==0)
                {
                    c[y][x] = 1;
                    t[x]++;
                }
            }
            int p = panduan();
            if(flag==0)
            {
                if(p == 1)
                {
                    flag = 1;
                    printf("Sorted sequence determined after %d relations: ",ydr);
                    cout<<s<<'.'<<'\n';
                }
                else if(p == 0)
                {
                    flag = 1;
                    printf("Inconsistency found after %d relations.\n",ydr);

                }
            }
        }
        if(flag == 0)
            printf("Sorted sequence cannot be determined.\n");
    }
    return 0;
}

 

發佈了41 篇原創文章 · 獲贊 10 · 訪問量 3498
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章