HDU2647 (topology sort + reverse build)

Source: Internet
Author: User

Test instructions not to say, said the idea.

The relationship is that a requires more pay than B, because as much as possible to let the boss pay less money, then A's salary is B's salary +1. To determine the relationship as a>b, the principle of building the edge based on topological ordering is to treat the "less than" relationship as a forward edge. Then we can build v->u.

#include <stdio.h> #include <string.h> #include <string> #include <iostream> #include < algorithm> #include <vector> #include <math.h> #include <map> #include <queue> #include < stack> #include <set> #define M 10000+5#define LL long long#define Ld __int64#define eps 0.00001#define INF 9999999 99#define MOD 112233#define MAX 26#define PI acos ( -1.0) using namespace std;vector<int> g[m];int num[m];int n;int int O[m],ans;int toposort () {queue<int> q;int cnt=0;ans=0;for (int i=1;i<=n;i++) {if (into[i]==0)// 0 points into the queue q.push (i);} while (!q.empty ()) {Cnt++;int U=q.front (), Ans+=num[u];q.pop (); for (int i=0;i<g[u].size (); i++) {int v=g[u][i];if (-- into[v]==0)//If the Edge is deleted (U,V), the degree of V is also 0, then pressed into the queue {Q.push (v); num[v]=num[u]+1;//v requires a higher salary than U}}}if (cnt!=n)//inference has no ring. -1 indicates a ring. 1 means no ring ans=-1;return ans;} int main () {int m;while (~scanf ("%d%d", &n,&m)) {for (int i=0;i<=n;i++) {g[i].clear (); into[i]=0;num[i]=888;} while (m--) {int u,v;scanf ("%d%d", &u,&v); G[v].pUsh_back (u); into[u]++;} printf ("%d\n", Toposort ());} return 0;} /*5 42 12 55 33 4*/


HDU2647 (topology sort + reverse build)

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.