1, the Messenger
(Message.pas/c/cpp)
"Problem description"
Students from the interest group from various schools, in order to increase the friendship, the party has a word of the game, if a know B, then a received a message, it will pass this message to B, and all the people who know.
If a knows b,b not necessarily know a.
All the people from 1 to n numbers, give all "understanding" relationship, ask if I release a message, then will pass through a number of messages, this message back to I,1<=i<=n.
"Input File"
The first line in the input file message.in is two numbers n (n<1000) and M (m<10000), with a space between two numbers indicating the number and the cognitive relationship.
The next m line, two numbers a and b per line, represents a knowing B. 1<=a,b<=n. The cognitive relationship may be repeated, but a line of two numbers will not be the same.
"Output File"
Output file Message.out A total of n rows, one character T or F per line. Line I if it is T, I send a message back to I; if it is F, I send a message that does not pass back to I.
"Input Sample"
4 6
1 2
2 3
4 1
3 1
1 3
2 3
"Output Sample"
T
T
T
F
In fact, this problem is only using a DFS, for each point search once, see whether can search the starting point, O (n^2) algorithm can also pass.
I used a tarjan, if the strong connected component is greater than 1, the ring, O (n) is indicated.
Relatively fixed, or very simple.
#include <algorithm> #include <cstdio> using Std::min;
struct Node {long ind;
Node* NXT;
};
node* head[1010];
Long Getint () {long rs=0;bool Sgn=1;char tmp;
do tmp = GetChar ();
while (!isdigit (TMP) &&tmp-'-');
if (tmp== '-') {Tmp=getchar (); sgn=0;}
Do rs= (rs<<1) + (rs<<3) +tmp-' 0 ';
while (IsDigit (Tmp=getchar ()));
return sgn?rs:-rs;
} void Insert (long A,long b) {node* NN = new node;
NN-> ind = b;
nn-> nxt = head[a];
Head[a] = nn;
Long time = 0;
Long bcnt = 0;
Long belong[1010];
Long dfn[1010];
Long low[1010];
BOOL instack[1010];
Long stack[1010];
BOOL hash[1010][1010];
Long cnt[1010];
Long top = 0;
void Tarjan (Long u) {dfn[u] = low[u] = ++time;
Stack[++top] = u;
Instack[u] = true;
for (node* vv=head[u];vv;vv=vv->nxt) {Long v = vv->ind; if (!
Dfn[v]) {Tarjan (v);
Low[u] = min (low[u],low[v]);
else if (Instack[v]) {Low[u] = min (low[u],dfn[v));
} if (dfn[u] = = Low[u]) {bcnt + +;
Long V; Do {v = stack[top--];
INSTACK[V] = false;
BELONG[V] = bcnt;
CNT[BCNT] + +;
}while (U!= v);
int main () {freopen ("message.in", "R", stdin);
Freopen ("Message.out", "w", stdout);
Long n = getint ();
Long m = Getint ();
for (long i=1;i<m+1;i++) {Long a = Getint ();
Long B = Getint ();
if (!hash[a][b]) {hash[a][b] = true;
Insert (A,B); for (long i=1;i<n+1;i++) if (!
Dfn[i]) Tarjan (i);
for (long i=1;i<n+1;i++) {if (Cnt[belong[i]] > 1) printf ("t\n");
else printf ("f\n");
return 0;
}