Uva10158-war (and collection)
Topic links
The main topic: There are n countries, each country has friends and enemies, and abide by friends friends are friends, enemy enemies are friends of the principle, give you four kinds of operation, the topic has a description, and then let you according to the operation, corresponding output corresponding results.
Problem-solving ideas: There are hostile relations and friends in the topic, friends can use and check the relationship, but the relationship is not hostile. Conversion of hostile relationships. Suppose 0~n-1, representing the country. N~2 * N-1 represents 0~n-1 of these countries ' enemies. For example 1 and 4 are hostile relationships, because enemy enemies are friends, then 1 + N and 4 with 1 and 4 + n is a friend relationship that converts a hostile relationship into a friend relationship, then a friend's relationship can be used and the difference is set (a friend has a transitive relationship).
Code:
#include <cstdio>#include <cstring>Const intMAXN =10005;intNintP[MAXN *2];voidInit () { for(inti =0; I <2N i++) P[i] = i; }intGetParent (intx) {returnx = = P[x]? X:P[X] = getParent (p[x]); }BOOLSetfriend (intXintY) {intX1 = getParent (x);intY1 = getParent (y);intx2 = getParent (x + N);inty2 = getParent (y + N);if(x1 = = Y2 | | y1 = = x2)return false;Else{p[x1] = y1; P[X2] = y2;return true; }}BOOLSetenemies (intXintY) {intX1 = getParent (x);intY1 = getParent (y);intx2 = getParent (x + N);inty2 = getParent (y + N);if(x1 = = Y1 | | y2 = = x2)return false;Else{p[x1] = y2; P[Y1] = x2;return true; }}BOOLIs_friend (intXintY) {intX1 = getParent (x);intY1 = getParent (y);intx2 = getParent (x + N);inty2 = getParent (y + N);if(x1 = = y1)return true;return false; }BOOLIs_enemies (intXintY) {intX1 = getParent (x);intY1 = getParent (y);intx2 = getParent (x + N);inty2 = getParent (y + N);if(x1 = = Y2 | | x2 = = y1)return true;return false; }intMain () {intOP, x, y;scanf("%d", &n); Init (); while(scanf("%d%d%d", &op, &x, &y)! = EOF && (OP | | x | | y)) {if(OP = =1) {if(Setfriend (x, y) = =false)printf(" -1\n"); }Else if(OP = =2) {if(Setenemies (x, y) = =false)printf(" -1\n"); }Else if(OP = =3)printf("%d\n", Is_friend (x, y));Else printf("%d\n", Is_enemies (x, y)); }return 0;}
Uva10158-war (and collection)