Can I Post the letter

Description

I am a traveler. I want to post a letter to Merlin. But because there are so many roads I can walk through, and maybe I can’t go to Merlin’s house following these roads, I must judge whether I can post the letter to Merlin before starting my travel. 

Suppose the cities are numbered from 0 to N-1, I am at city 0, and Merlin is at city N-1. And there are M roads I can walk through, each of which connects two cities. Please note that each road is direct, i.e. a road from A to B does not indicate a road from B to A.

Please help me to find out whether I could go to Merlin’s house or not.

Input

There are multiple input cases. For one case, first are two lines of two integers N and M, (N<=200, M<=N*N/2), that means the number of citys and the number of roads. And Merlin stands at city N-1. After that, there are M lines. Each line contains two integers i and j, what means that there is a road from city i to city j.

The input is terminated by N=0.

Output

For each test case, if I can post the letter print “I can post the letter” in one line, otherwise print “I can't post the letter”.

題目解釋:這道題主要找出從起點0到終點N-1是否有可行路徑。其中會給出這N個城市中道路想通的情況。這是一個有向圖,求出有向圖中從0到N-1是否有解。可以使用廣度優先搜索算法。

#include <iostream>
#include <map>
#include <vector>
#include <stack>
using namespace std;
int main(int argc, const char * argv[]) {
    // insert code here...
    int cityNum;
    while(cin >> cityNum && cityNum){
        int roadNum;
        int start,dest;
        cin >> roadNum;
        map<int, vector<int> > graph;
        vector<bool> flag(cityNum);
        for (int i = 0; i< roadNum; i++) { // 存儲圖的數據
            cin >> start >> dest;
            graph[start].push_back(dest);
        }
        stack<int> st;
        st.push(0);
        flag[0]=false;
        bool result = false;
        while (!st.empty()) { // 使用廣度優先搜索
            int popNum = st.top();
            st.pop();
            if (popNum == cityNum-1) {
                result = true;
                break;
            }
            for (int i = 0; i < graph[popNum].size(); i++) {
                if (flag[graph[popNum][i]]) {
                    continue;
                }
                flag[graph[popNum][i]] = true;
                st.push(graph[popNum][i]);
            }
        }
        if (result) cout << "I can post the letter" << endl;
        else cout << "I can't post the letter" << endl;
    }
    
    return 0;
}


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