Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <set>
- using namespace std;
- // matrix is 1 based.
- bool matrix[50][50]={false};
- //add edge
- void addfriend(int a, int b) {
- matrix[a][b] = true;
- matrix[b][a] = true;
- }
- //remove edge
- void unfriend(int a, int b) {
- matrix[a][b] = false;
- matrix[b][a] = false;
- }
- //count friends
- void n(int x) {
- int count=0;
- //through the row of x, count how many times there is an edge. = num of friends
- for(int i=1; i<50; i++) {
- if(matrix[x][i]) {
- count++;
- }
- }
- cout << count << "\n";
- }
- //count friends of friends
- void f(int x) {
- set<int> friends; //this set will contain direct friends and x himself
- set<int> foff; //this set will contain friends of friends
- friends.insert(x); //insert themself into the set
- //add to set friends
- for(int i=1; i<50; i++) {
- //if there is an edge
- if(matrix[x][i]) {
- //if not in set already
- if(friends.count(i) == 0) {
- friends.insert(i);
- }
- }
- }
- //loop through friends of friends
- for(int i=1; i<50; i++) {
- if(matrix[x][i]) {
- for(int j=1; j<50; j++) {
- if(matrix[i][j]) {
- //if the friend is not in direct friends
- if(friends.count(j) == 0) {
- //if the friend has not been seen before in friends of freinds
- if(foff.count(j) == 0) {
- foff.insert(j); //insert the friend into friends of friends set
- }
- }
- }
- }
- }
- }
- cout << foff.size() << "\n";
- }
- //Floyd–Warshall algorithm
- void s(int x, int y) {
- int dist[50][50];
- for(int i=1; i<50; i++) {
- for(int j=1; j<50; j++) {
- if(i==j) {
- dist[i][j] = 0;
- } else if(matrix[i][j]) {
- dist[i][j] = 1;
- } else {
- dist[i][j] = 1000; //infinity
- }
- }
- }
- for(int k=1; k<50; k++) {
- for(int i=1; i<50; i++) {
- for(int j=1; j<50; j++) {
- if(dist[i][j] > dist[i][k] + dist[k][j]) {
- dist[i][j] = dist[i][k] + dist[k][j];
- }
- }
- }
- }
- if(dist[x][y]==1000) {
- cout << "Not connected\n";
- } else {
- cout << dist[x][y] << "\n";
- }
- }
- int main() {
- cin.sync_with_stdio(0);
- cin.tie(0);
- addfriend(1, 6);
- addfriend(2, 6);
- addfriend(3, 6);
- addfriend(3, 4);
- addfriend(3, 5);
- addfriend(3, 15);
- addfriend(4, 6);
- addfriend(5, 6);
- addfriend(6, 7);
- addfriend(7, 8);
- addfriend(8, 9);
- addfriend(9, 10);
- addfriend(9, 12);
- addfriend(10, 11);
- addfriend(11, 12);
- addfriend(12, 13);
- addfriend(13, 15);
- addfriend(13, 14);
- addfriend(16, 17);
- addfriend(17, 18);
- addfriend(16, 18);
- char command;
- cin >> command;
- while(command != 'q') {
- int x, y;
- switch(command) {
- case 'i':
- cin >> x >> y;
- addfriend(x, y);
- break;
- case 'd':
- cin >> x >> y;
- unfriend(x, y);
- break;
- case 'n':
- cin >> x;
- n(x);
- break;
- case 'f':
- cin >> x;
- f(x);
- break;
- case 's':
- cin >> x >> y;
- s(x, y);
- }
- cin >> command;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement