Going from u to v or from v to u?
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 12201 | Accepted: 3125 |
Description
Input
The first line for each case contains two integers n, m(0 < n < 1001,m < 6000), the number of rooms and corridors in the cave. The next m lines each contains two integers u and v, indicating that there is a corridor connecting room u and room v directly.
Output
Sample Input
1 3 3 1 2 2 3 3 1
Sample Output
Yes
Source
- #include<cstdio>
- #include<algorithm>
- using namespace std;
- struct node
- {
- int x,y;
- };
- int s[1010],e[1010];
- struct node a[7000];
- int Stop,Bcnt,Dindex;
- int DFN[1010],LOW[1010];
- int n,m;
- int Stap[1010];
- int Belong[1010];
- bool map[1010][1010];
- bool instack[1010];
- bool cmp(struct node a,struct node b)
- {
- if (a.x < b.x) return true;
- if (a.x == b.x && a.y < b.y) return true;
- return false;
- }
- void tarjan(int k)
- {
- DFN[k] = LOW[k] = ++Dindex;
- instack[k] = true;
- Stap[++Stop] = k;
- for (int i = s[k] ; i <= e[k] ; i++)
- {
- int j = a[i].y;
- if (!DFN[j])
- {
- tarjan(j);
- if (LOW[j] < LOW[k]) LOW[k] = LOW[j];
- }
- else
- if (instack[j] && DFN[j] < LOW[k]) LOW[k] = DFN[j];
- }
- if (DFN[k] == LOW[k])
- {
- Bcnt++;
- while (1)
- {
- int j = Stap[Stop--];
- instack[j] = false;
- Belong[j] = Bcnt;
- if (j == k) break;
- }
- }
- }
- void solve()
- {
- Stop=Bcnt=Dindex=0;
- for (int i = 1 ; i <= n ; i++) DFN[i] = 0;
- for (int i = 1 ; i <= n ; i++)
- if (!DFN[i]) tarjan(i);
- }
- int main()
- {
- int t;
- scanf("%d",&t);
- while (t--)
- {
- scanf("%d%d",&n,&m);
- for (int i = 0 ; i < m ; i++) scanf("%d%d",&a[i].x,&a[i].y);
- sort(a,a+m,cmp);
- for (int i = 1 ; i <= n ; i++)
- {
- s[i] = m;
- e[i] = -1;
- }
- for (int i = 0 ; i < m ; i++)
- {
- if (i < s[a[i].x]) s[a[i].x] = i;
- if (i > e[a[i].x]) e[a[i].x] = i;
- }
- solve();
- for (int i = 1 ; i <= Bcnt ; i++)
- for (int j = 1 ; j <= Bcnt ; j++)
- map[i][j] = false;
- for (int i = 0 ; i < m ; i++)
- map[Belong[a[i].x]][Belong[a[i].y]] = true;
- int enter = 0;
- int out = 0;
- for (int i = 1 ; i <= Bcnt ; i++)
- {
- bool flag1 = false;
- bool flag2 = false;
- for (int j = 1 ; j <= Bcnt ; j++)
- if (i != j)
- {
- if (map[i][j]) flag1 = true;
- if (map[j][i]) flag2 = true;
- }
- if (!flag1) out++;
- if (!flag2) enter++;
- }
- if (out > 1 || enter > 1) printf("No\n");
- else printf("Yes\n");
- }
- return 0;
- }