Hdoj 3342 legal or not [topological sorting]

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.