Kame3

Социјална мрежа lab9.3

Jan 12th, 2021 (edited)
812
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.16 KB | None | 0 0
  1. Социјална мрежа Problem 3 (0 / 0)
  2.  
  3. Дадена е една социјална мрежа (Facebook) во која за корисниците се чуваат податоци за реден број (целобројна вредност), име и презиме. Исто така, за секој корисник познати се неговите пријатели во социјалната мрежа. Да се напише алгоритам кој за дадени редни броеви на двајца корисници го одредува степенот на разделеност помеѓу корисниците т.е. преку колку најмалку корисници се поврзани (преку колку најмалку корисници може да се стигне од едниот до другиот корисник) во социјалната мрежа. Социјалната мрежа е претставена како нетежински граф со листа на соседство. Во првиот ред од влезот е даден бројот на корисниците. Потоа, во следниот ред е даден бројот на пријателите на првиот корисник (со реден број 0), и во следните редови се наведени неговите пријатели со реден број, име и презиме. Понатаму се дадени на истиот начин информациите за сите корисници. На крај во последните два реда се дадени редните броеви на двата корисници за кои треба да се одреди степенот на разделеност.
  4.  
  5. Име на класата: CountFacebookFriends
  6.  
  7.  
  8. import java.util.Scanner;
  9. import java.util.LinkedList;
  10. import java.util.Iterator;
  11. import java.util.Stack;
  12. import java.util.NoSuchElementException;
  13. import java.io.IOException;
  14. import java.io.InputStreamReader;
  15.    
  16. public class CountFacebookFriends {
  17.  
  18.    
  19.     public static void main(String[] args) {
  20.         Scanner in = new Scanner(System.in);
  21.         int n = in.nextInt();
  22.        
  23.         GraphNode<User>[] niza = new GraphNode[n];
  24.         int mat[][] = new int[n][n];
  25.        
  26.         for (int i = 0; i < n; i++)
  27.             for (int j = 0; j < n; j++)
  28.                 mat[i][j] = 0;
  29.        
  30.         for (int i = 0; i < n; i++) {
  31.             int friends = in.nextInt();
  32.            
  33.             for (int j = 0; j < friends; j++) {
  34.                 int index = in.nextInt();
  35.                 String name = in.next();
  36.                 String lastname = in.next();
  37.                
  38.                
  39.                 User user = new User(index, name, lastname);
  40.                
  41.                 mat[i][index] = 1;
  42.                 mat[index][i] = 1;
  43.                
  44.                 GraphNode<User> pom = new GraphNode<User>(index, user);
  45.                 niza[index] = pom;
  46.             }
  47.         }
  48.        
  49.         Graph g = new Graph(n, niza);
  50.        
  51.         for (int i = 0; i < n; i++)
  52.         for (int j = 0; j < n; j++) {
  53.             if (mat[i][j] == 1) {
  54.                 g.addEdge(i, j);
  55.             }
  56.         }
  57.        
  58.         int a = in.nextInt();
  59.         int b = in.nextInt();
  60.        
  61.         if (a == b){
  62.             System.out.println("0");
  63.             return;
  64.         }
  65.        
  66.         int dist[] = new int[n];
  67.         boolean visited[] = new boolean[n];
  68.        
  69.         for (int i = 0; i < n; i++) {
  70.             visited[i] = false;
  71.             dist[i] = 0;
  72.         }
  73.            
  74.        
  75.         visited[a] = true;
  76.  
  77.         Queue<Integer> q = new LinkedQueue<Integer>();
  78.         q.enqueue(a);
  79.        
  80.         while (!q.isEmpty()) {
  81.             int pom = q.dequeue();
  82.            
  83.             for (int i = 0; i < n; i++) {
  84.                 if (g.adjacent(pom, i) == 1) {
  85.                     if (!visited[i]) {
  86.                         visited[i] = true;
  87.                         dist[i] = dist[pom] + 1;
  88.                         q.enqueue(i);
  89.                        
  90.                         if (i == b) {
  91.                             System.out.print(dist[i]);
  92.                             return;
  93.                         }
  94.                     }
  95.                 }
  96.             }
  97.         }
  98.        
  99.     }
  100. }
  101.  
  102. class User {
  103.     int index;
  104.     String name, lastname;
  105.    
  106.     public User(int index, String name, String lastname) {
  107.         this.index = index;
  108.         this.name = name;
  109.         this.lastname = lastname;
  110.     }
  111.    
  112.     @Override
  113.     public String toString() {
  114.         return index +", " + name + ", " + lastname;
  115.  
  116.     }
  117. }
  118.  
  119. class Graph<E> {
  120.  
  121.     int num_nodes;
  122.     GraphNode<E> adjList[];
  123.  
  124.     @SuppressWarnings("unchecked")
  125.     public Graph(int num_nodes, E[] list) {
  126.         this.num_nodes = num_nodes;
  127.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  128.         for (int i = 0; i < num_nodes; i++)
  129.             adjList[i] = new GraphNode<E>(i, list[i]);
  130.     }
  131.  
  132.     @SuppressWarnings("unchecked")
  133.     public Graph(int num_nodes) {
  134.         this.num_nodes = num_nodes;
  135.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  136.     }
  137.  
  138.     int adjacent(int x, int y) {
  139.         // proveruva dali ima vrska od jazelot so
  140.         // indeks x do jazelot so indeks y
  141.         return (adjList[x].containsNeighbor(adjList[y])) ? 1 : 0;
  142.     }
  143.  
  144.     void addEdge(int x, int y) {
  145.         // dodava vrska od jazelot so indeks x do jazelot so indeks y
  146.         if (!adjList[x].containsNeighbor(adjList[y])) {
  147.             adjList[x].addNeighbor(adjList[y]);
  148.         }
  149.     }
  150.  
  151.     void deleteEdge(int x, int y) {
  152.         adjList[x].removeNeighbor(adjList[y]);
  153.     }
  154.  
  155.     void dfsSearch(int node) {
  156.         boolean visited[] = new boolean[num_nodes];
  157.         for (int i = 0; i < num_nodes; i++)
  158.             visited[i] = false;
  159.         dfsRecursive(node, visited);
  160.     }
  161.  
  162.     void dfsRecursive(int node, boolean visited[]) {
  163.         visited[node] = true;
  164.         System.out.println(node + ": " + adjList[node].getInfo());
  165.  
  166.         for (int i = 0; i < adjList[node].getNeighbors().size(); i++) {
  167.             GraphNode<E> pom = adjList[node].getNeighbors().get(i);
  168.             if (!visited[pom.getIndex()])
  169.                 dfsRecursive(pom.getIndex(), visited);
  170.         }
  171.     }
  172.  
  173.     void dfsNonrecursive(int node) {
  174.         boolean visited[] = new boolean[num_nodes];
  175.         for (int i = 0; i < num_nodes; i++)
  176.             visited[i] = false;
  177.         visited[node] = true;
  178.         System.out.println(node+": " + adjList[node].getInfo());
  179.         Stack<Integer> s = new Stack<Integer>();
  180.         s.push(node);
  181.  
  182.         GraphNode<E> pom;
  183.  
  184.         while (!s.isEmpty()) {
  185.             pom = adjList[s.peek()];
  186.             GraphNode<E> tmp=null;
  187.             for (int i = 0; i < pom.getNeighbors().size(); i++) {
  188.                 tmp = pom.getNeighbors().get(i);
  189.                 if (!visited[tmp.getIndex()])
  190.                     break;
  191.             }
  192.             if(tmp!=null&&!visited[tmp.getIndex()]){
  193.                 visited[tmp.getIndex()] = true;
  194.                 System.out.println(tmp.getIndex() + ": " + tmp.getInfo());
  195.                 s.push(tmp.getIndex());
  196.             }
  197.             else
  198.                 s.pop();
  199.         }
  200.  
  201.     }
  202.    
  203.     void bfs(int node){
  204.         boolean visited[] = new boolean[num_nodes];
  205.         for (int i = 0; i < num_nodes; i++)
  206.             visited[i] = false;
  207.         visited[node] = true;
  208.         System.out.println(node+": " + adjList[node].getInfo());
  209.         Queue<Integer> q = new LinkedQueue<Integer>();
  210.         q.enqueue(node);
  211.        
  212.         GraphNode<E> pom;
  213.        
  214.         while(!q.isEmpty()){
  215.             pom = adjList[q.dequeue()];
  216.             GraphNode<E> tmp=null;
  217.             for (int i = 0; i < pom.getNeighbors().size(); i++) {
  218.                 tmp = pom.getNeighbors().get(i);
  219.                 if (!visited[tmp.getIndex()]){
  220.                     visited[tmp.getIndex()] = true;
  221.                     System.out.println(tmp.getIndex()+": " + tmp.getInfo());
  222.                     q.enqueue(tmp.getIndex());
  223.                 }
  224.             }
  225.            
  226.            
  227.         }
  228.        
  229.     }
  230.    
  231.  
  232.     @Override
  233.     public String toString() {
  234.         String ret = new String();
  235.         for (int i = 0; i < this.num_nodes; i++)
  236.             ret += i + ": " + adjList[i] + "\n";
  237.         return ret;
  238.     }
  239.  
  240. }
  241.  
  242. class GraphNode<E> {
  243.     private int index;//index (reden broj) na temeto vo grafot
  244.     private E info;
  245.     private LinkedList<GraphNode<E>> neighbors;
  246.    
  247.     public GraphNode(int index, E info) {
  248.         this.index = index;
  249.         this.info = info;
  250.         neighbors = new LinkedList<GraphNode<E>>();
  251.     }
  252.    
  253.     boolean containsNeighbor(GraphNode<E> o){
  254.         return neighbors.contains(o);
  255.     }
  256.    
  257.     void addNeighbor(GraphNode<E> o){
  258.         neighbors.add(o);
  259.     }
  260.    
  261.     void removeNeighbor(GraphNode<E> o){
  262.         if(neighbors.contains(o))
  263.             neighbors.remove(o);
  264.     }
  265.    
  266.     @Override
  267.     public String toString() {
  268.         String ret= "INFO:"+info+" SOSEDI:";
  269.         for(int i=0;i<neighbors.size();i++)
  270.         ret+=neighbors.get(i).info+" ";
  271.         return ret;
  272.        
  273.     }
  274.  
  275.     @Override
  276.     public boolean equals(Object obj) {
  277.         @SuppressWarnings("unchecked")
  278.         GraphNode<E> pom = (GraphNode<E>)obj;
  279.         return (pom.info.equals(this.info));
  280.     }
  281.  
  282.     public int getIndex() {
  283.         return index;
  284.     }
  285.  
  286.     public void setIndex(int index) {
  287.         this.index = index;
  288.     }
  289.  
  290.     public E getInfo() {
  291.         return info;
  292.     }
  293.  
  294.     public void setInfo(E info) {
  295.         this.info = info;
  296.     }
  297.  
  298.     public LinkedList<GraphNode<E>> getNeighbors() {
  299.         return neighbors;
  300.     }
  301.  
  302.     public void setNeighbors(LinkedList<GraphNode<E>> neighbors) {
  303.         this.neighbors = neighbors;
  304.     }
  305.  
  306.    
  307.    
  308. }
  309.  class LinkedQueue<E> implements Queue<E> {
  310.  
  311.     // Redicata e pretstavena na sledniot nacin:
  312.     // length go sodrzi brojot na elementi.
  313.     // Elementite se zachuvuvaat vo jazli dod SLL
  314.     // front i rear se linkovi do prviot i posledniot jazel soodvetno.
  315.     SLLNode<E> front, rear;
  316.     int length;
  317.  
  318.     // Konstruktor ...
  319.  
  320.     public LinkedQueue () {
  321.         clear();
  322.     }
  323.  
  324.     public boolean isEmpty () {
  325.         // Vrakja true ako i samo ako redicata e prazena.
  326.         return (length == 0);
  327.     }
  328.  
  329.     public int size () {
  330.         // Ja vrakja dolzinata na redicata.
  331.         return length;
  332.     }
  333.  
  334.     public E peek () {
  335.         // Go vrakja elementot na vrvot t.e. pocetokot od redicata.
  336.         if (front == null)
  337.             throw new NoSuchElementException();
  338.         return front.element;
  339.     }
  340.  
  341.     public void clear () {
  342.         // Ja prazni redicata.
  343.         front = rear = null;
  344.         length = 0;
  345.     }
  346.  
  347.     public void enqueue (E x) {
  348.         // Go dodava x na kraj od redicata.
  349.         SLLNode<E> latest = new SLLNode<E>(x, null);
  350.         if (rear != null) {
  351.             rear.succ = latest;
  352.             rear = latest;
  353.         } else
  354.             front = rear = latest;
  355.         length++;
  356.     }
  357.  
  358.     public E dequeue () {
  359.         // Go otstranuva i vrakja pochetniot element na redicata.
  360.         if (front != null) {
  361.             E frontmost = front.element;
  362.             front = front.succ;
  363.             if (front == null)  rear = null;
  364.             length--;
  365.             return frontmost;
  366.         } else
  367.             throw new NoSuchElementException();
  368.     }
  369.  
  370. }
  371.  
  372. interface Queue<E> {
  373.  
  374.     // Elementi na redicata se objekti od proizvolen tip.
  375.  
  376.     // Metodi za pristap:
  377.  
  378.     public boolean isEmpty ();
  379.         // Vrakja true ako i samo ako redicata e prazena.
  380.  
  381.     public int size ();
  382.         // Ja vrakja dolzinata na redicata.
  383.  
  384.     public E peek ();
  385.         // Go vrakja elementot na vrvot t.e. pocetokot od redicata.
  386.  
  387.     // Metodi za transformacija:
  388.  
  389.     public void clear ();
  390.         // Ja prazni redicata.
  391.  
  392.     public void enqueue (E x);
  393.         // Go dodava x na kraj od redicata.
  394.  
  395.     public E dequeue ();
  396.         // Go otstranuva i vrakja pochetniot element na redicata.
  397.  
  398. }
  399.  
  400. class SLLNode<E> {
  401.     protected E element;
  402.     protected SLLNode<E> succ;
  403.  
  404.     public SLLNode(E elem, SLLNode<E> succ) {
  405.         this.element = elem;
  406.         this.succ = succ;
  407.     }
  408.  
  409.     @Override
  410.     public String toString() {
  411.         return element.toString();
  412.     }
  413. }
  414.  
  415.  
  416. Sample input
  417.  
  418. 3
  419. 2
  420. 1 Ilinka Ivanoska
  421. 2 Igor Kulev
  422. 1
  423. 0 Magdalena Kostoska
  424. 1
  425. 0 Magdalena Kostoska
  426. 0
  427. 1
  428.  
  429. Sample output
  430.  
  431. 1
  432.  
  433. Simple Input:
  434. 6
  435. 1
  436. 1 Ilinka Ivanoska
  437. 2
  438. 0 Magdalena Kostoska
  439. 2 Igor Kulev
  440. 2
  441. 1 Ilinka Ivanoska
  442. 3 Vladimir Trajkovik
  443. 2
  444. 2 Igor Kulev
  445. 4 Anastas Misev
  446. 2
  447. 3 Vladimir Trajkovik
  448. 5 Slobodan Kalajdziski
  449. 1
  450. 4 Anastas Misev
  451. 1
  452. 5
  453.  
  454.    
  455. Simple Output:
  456.  
  457. 4
  458.  
  459.  
Add Comment
Please, Sign In to add comment