Question: Determine whether a ring is formed.
Policy: for example, question.
This is a simple Topology Sorting question, but pay attention to the repeated data. I used two types of struct: chained forward star and Adjacent matrix.
Code 1: (use the chain forward star) (do not add deduplication)
#include<stdio.h>#include<string.h>#include<queue>#define INF 0x3f3f3f3f#define MAXN 105struct EdgeNode{int to;int next;}edges[MAXN];int head[MAXN], n, in[MAXN], queue[MAXN];int toposort(){int i, iq = 0, j;for(i = 0; i < n; i ++){if(!in[i]){queue[iq++] = i;}}for(i = 0; i < iq; i ++){int temp = queue[i];for(j = head[temp]; j != -1; j = edges[j].next){if(!--in[edges[j].to]){queue[iq++] = edges[j].to;}}}return iq == n;}int main(){int m, a, b, i;while(scanf("%d%d", &n, &m), n||m){memset(head, -1, sizeof(head));memset(in, 0, sizeof(in));for(i = 0; i < m; i ++){scanf("%d%d", &a, &b);edges[i].to = b;edges[i].next = head[a];head[a] = i;++in[b];}printf("%s\n", toposort()?"YES":"NO");}}
Code 2: (using an adjacent matrix) facts prove that chained forward stars are faster
# Include <stdio. h> # include <string. h >#include <queue> # define INF 0x3f3f3f3f # define maxn 105int map [105] [105]; int queue [maxn], in [maxn]; int N; int toposort () {int I, j; int IQ = 0; for (I = 0; I <n; I ++) {If (! In [I]) {queue [IQ ++] = I ;}} for (I = 0; I <IQ; I ++) {int temp = queue [I]; for (j = 0; j <n; j ++) {If (Map [temp] [J]) {-- in [J]; If (! In [J]) {queue [IQ ++] = J ;}}} return IQ = n ;}int main () {int M, I, j,, b; while (scanf ("% d", & N, & M), N | M) {memset (MAP, 0, sizeof (MAP )); memset (in, 0, sizeof (in); for (I = 0; I <m; I ++) {scanf ("% d", &, & B); If (! Map [a] [B]) {// deduplicated map [a] [B] = 1; in [B] ++ ;}} printf ("% s \ n", toposort ()? "Yes": "no");} return 0 ;}
Question link: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 3342