解決圖論問題,首先就要思考用什么樣的方式存儲圖。但是小鑫卻怎么也弄不明白如何存圖才能有利于解決問題。你能幫他解決這個問題么?
每一組第一行有兩個數n、m表示n個點,m條有向邊。接下來有m行,每行兩個數u、v代表u到v有一條有向邊。第m+2行有一個數q代表詢問次數,接下來q行每行有一個詢問,輸入兩個數為a,b。
注意:點的編號為0~n-1,2<=n<=500000,0<=m<=500000,0<=q<=500000,a!=b,輸入保證沒有自環和重邊
2 10 120 11 0Example Output
YesNo#include <iostream>#include <stdlib.h>#include <string.h>#include <stdio.h>using namespace std;
struct node{ int data; struct node * next;};
int main(){ ios::sync_with_stdio(false);
int m, n; struct node * head[500001], *p, *temp;
while(cin >> n >> m) { for(int i = 0; i < n; i++) head[i] = NULL;//初始化鏈表頭,對應每個點都有一個鏈表
for(int i = 0; i < m; i++)//輸入兩點,確定連線 { int u, v; cin >> u >> v; //當輸入的點還沒有建立鏈表的時候,開辟內存,存入數據 if(head[u] == NULL) { head[u] = (struct node *)malloc(sizeof(struct node)); head[u]->data = v; head[u]->next = NULL; } //當輸入的點已經開辟了內存建立了鏈表,通過逆序建立鏈表的方法,存入數據 else { temp = head[u]->next; p = (struct node *)malloc(sizeof(struct node)); p->data = v; p->next = temp; head[u]->next = p; } } int q; cin >> q; for(int i = 0; i < q; i++) { int x, y; int flag = 0; cin >> x >> y; //當輸入數據沒有建立鏈表則不能連通 if(head[x] == NULL) cout << "No" << endl; else { //從當前點開始遍歷整個鏈表,當遇到輸入的數據的時候,flag賦值跳出 temp = head[x]; while(temp != NULL) { if(temp->data == y) { flag = 1; break; } temp = temp->next; } if(flag == 1) cout << "Yes" << endl; else cout << "No" << endl; } } } return 0;}
新聞熱點
疑難解答