poj 1270 Following Orders(拓撲排序+dfs)

來源:互聯網
上載者:User

標籤:拓撲排序   dfs   

大致題意:每個範例包含兩行,第一行輸入n個字元,可能是無序的。第二行輸入成對的a b,代表a要在b前面。輸出所有的符合這樣的序列。


思路:很明顯的拓撲排序。要輸出所有的序列,那麼就從入度為0的點進行dfs,每次選擇一個入度為0的點,加入輸出序列並把與它相鄰的點的入度減一。dfs結束後要把狀態再改回來。

#include <stdio.h>#include <algorithm>#include <set>#include <map>#include <vector>#include <math.h>#include <string.h>#include <stack>#include <queue>#define LL long long#define _LL __int64using namespace std;const int maxn = 110;char contents[30];bool mapp[60][60];int n = 0;char t,t1,t2;int flag;int in[30];int vis[30];int ans[30];void dfs(int num){    if(num == n)    {        for(int i = 0; i < n; i++)            printf("%c",ans[i]);        printf("\n");        return;    }    for(int i = 0; i < n; i++)    {        if(!vis[i] && !in[ contents[i]-‘a‘ ])         {            for(int j = 0; j < n; j++)            {                if(mapp[contents[i]-‘a‘][contents[j]-‘a‘])                {                    in[ contents[j]-‘a‘]--;                }            }            ans[num] = contents[i];            vis[i] = 1;                        dfs(num+1);                        //注意將狀態更改回來            for(int j = 0; j < n; j++)            {                if(mapp[contents[i]-‘a‘][contents[j]-‘a‘])                {                    in[ contents[j]-‘a‘]++;                }            }            vis[i] = 0;        }    }}int main(){    flag = 0;    while(~scanf("%c",&t))    {        if(t >= ‘a‘ && t <= ‘z‘)        {            contents[n++] = t;            continue;        }        else if(t == ‘ ‘) continue;        else        {            if(flag)                printf("\n");            flag = 1;            sort(contents,contents+n); //因為輸入可能是無序的,先排序            memset(in,0,sizeof(in));            memset(mapp,false,sizeof(mapp));            memset(vis,0,sizeof(vis));            while(~scanf("%c %c",&t1,&t2))            {                mapp[t1-‘a‘][t2-‘a‘] = 1;                in[t2-‘a‘]++;                if(getchar() == ‘\n‘)                    break;            }                        dfs(0);            n = 0;        }    }    return 0;}







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.