首页 > 试题广场 >

比较重量

[编程题]比较重量
  • 热度指数:6293 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

小明陪小红去看钻石,他们从一堆钻石中随机抽取两颗并比较她们的重量。这些钻石的重量各不相同。在他们们比较了一段时间后,它们看中了两颗钻石g1和g2。现在请你根据之前比较的信息判断这两颗钻石的哪颗更重。

给定两颗钻石的编号g1,g2,编号从1开始,同时给定关系数组vector,其中元素为一些二元组,第一个元素为一次比较中较重的钻石的编号,第二个元素为较轻的钻石的编号。最后给定之前的比较次数n。请返回这两颗钻石的关系,若g1更重返回1,g2更重返回-1,无法判断返回0。输入数据保证合法,不会有矛盾情况出现。

测试样例:
2,3,[[1,2],[2,4],[1,3],[4,3]],4
返回: 1
int cmp(int g1, int g2, vector<vector<int> > records, int n) {
        int maxNum = -99999;
        for(int i=0; i<n; i++){
            maxNum = maxNum>records[i][0]?maxNum:records[i][0];
            maxNum = maxNum>records[i][1]?maxNum:records[i][1];
        }
        //构造有向图
        int map[maxNum+1][maxNum+1];
        for(int i=1; i<=maxNum; i++){
            for(int j=1; j<=maxNum; j++){
            	if(i == j) map[i][j] = 1;
                else  map[i][j] = 0;
            }            
        }
        for(int i=0; i<n; i++){
            map[records[i][0]][records[i][1]] = 1;
        }
         
        for(int k=1; k<=maxNum; k++){
            for(int j=1; j<=maxNum; j++){
                for(int i=1; i<=maxNum; i++){ 
                    if(map[i][k] == 1 && map[k][j] == 1){
                        map[i][j] = 1;                        
                    }
                }
            }
        }
        if(map[g1][g2] == 1)
            return 1;
        else if(map[g2][g1] == 1)
            return -1;
        else
        	return 0;
    }

编辑于 2016-07-31 20:47:07 回复(4)
//就是一个森林,关系存在就是以g2为根节点的树下面的节点中有g1,
//或者以g1为根节点的树的下面的节点包含g2
//我们采取层序遍历的方式遍历以g1开头的整棵树,和以g2开头的整棵树.
#include<unordered_map>
class Cmp {
    bool judge(int g1,int g2,unordered_map<int,vector<int>> ans){
    //查找g1是否比g2重.
        queue<int>q;
        unordered_map<int, bool>mark;//用于标记当前节点是否遍历过
        q.push(g1);
        while (!q.empty()) {
            int cur = q.front();
            q.pop();
            mark[cur] = true;
            if(cur==g2)
                return true;
            for(int i=0;i<ans[cur].size();++i){
                if(!mark[ans[cur][i]])//没有遍历过
                    q.push(ans[cur][i]);
            }
        }
        return false;
    }
public:
    int cmp(int g1, int g2, vector<vector<int> > records, int n) {
        unordered_map<int,vector<int>>ans;
        for (int i=0; i<n; ++i)
            ans[records[i][0]].push_back(records[i][1]);
        if(judge(g1, g2, ans))
            return 1;
        else{
            if(judge(g2, g1, ans))
                return -1;
            else
                return 0;
        }
    }
};

发表于 2016-03-27 18:25:38 回复(8)
 //题目相当于是求有向图中的两个节点的可达性,所以解这个题目分为两步,先构造有向图,再求可达性。
public class Cmp {

     private  boolean reachable = false;

    public int cmp(int g1, int g2, int[][] records, int n) {
        // 生成一个有向图
        HashMap<Integer, List<Integer>> map = generateMap(records, n);
        if (map.isEmpty()) {
            return 0;
        }
        depthSearch(g1, g2, map);
        if (reachable) {
            return 1;
        }
        depthSearch(g2, g1, map);
        if (reachable) {
            return -1;
        }
        return 0;
    }

    private void depthSearch(int g1, int g2, HashMap<Integer, List<Integer>> map) {
        if (!map.containsKey(g1)) {
            reachable = false;
        } else {
            List<Integer> values = map.get(g1);
            for (int value : values) {
                if (g2 == value) {
                    reachable = true;
                    return;
                } else {
                    depthSearch(value, g2, map);
                }
            }

        }
    }

    public HashMap<Integer, List<Integer>> generateMap(int[][] records, int n) {
        HashMap<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            int key = records[i][0];
            int value = records[i][1];
            if (map.containsKey(key)) {
                map.get(key).add(value);
            } else {
                List<Integer> list = new ArrayList<>();
                list.add(value);
                map.put(key, list);
            }
        }
        return map;
    }
  
}

编辑于 2016-08-01 20:19:10 回复(9)
弗洛伊德算法
importjava.util.*;
 
publicclassCmp {
    publicintcmp(intg1, intg2, int[][] records, intn) {
        // write code here
        intmax=records[0][0];
        for(inti=0;i<n;i++){
            max=max>records[i][0]?max:records[i][0];
            max=max>records[i][1]?max:records[i][1];
        }
        int[][] arr = newint[max+1][max+1];
        for(inti=0;i<n;i++){
            arr[records[i][0]][records[i][1]]=1;
        }
        for(intk=1;k<=max;k++){
            for(inti=1;i<=max;i++){
                for(intj=1;j<=max;j++){
                    if(arr[i][k]>0&&arr[k][j]>0){
                        arr[i][j]=arr[i][k]+arr[k][j];
                    }
                }
            }
        }
        if(arr[g1][g2]>0)
            return1;
        elseif(arr[g2][g1]>0)
            return-1;
        else
            return0;
    }
}
编辑于 2016-04-08 18:42:32 回复(5)
当做一个有向图来处理,生成邻接矩阵,可以采用dfs或bfs的方法。
但是我用dfs时,OJ一直超时。bfs可以通过。
-------------------------------------------------------------------------
BFS:
public class Cmp {
	public int cmp(int g1, int g2, int[][] records, int n) {
		int max = Integer.MIN_VALUE;
		for (int i = 0; i < n; ++i) {
			max = Math.max(Math.max(max, records[i][0]), records[i][1]);
		}
		// 生成图的邻接表
		int[][] map = new int[max + 1][max + 1];
		for (int i = 0; i < n; ++i) {
			map[records[i][0]][records[i][1]] = 1;
		}
		if(bfs(g1,g2,map))
			return 1;
		if(bfs(g2,g1,map))
			return -1;
		return 0;
	}
	private boolean bfs(int g1,int g2,int[][] map){
		boolean[] visited = new boolean[map.length];
		LinkedList<Integer> queue = new LinkedList<>();
		queue.add(g1);
		while(!queue.isEmpty()){
			int v = queue.removeFirst();
			visited[v] = true;
			for(int i = 0;i < map[0].length;++i){
				if(!visited[i] && map[v][i] != 0){
					if(i==g2)
						return true;
					queue.add(i);
				}
			}
		}
		return false;
	}
}
-------------------------------------------------------------------------
DFS:
public class Cmp {
	boolean flag = false;
	public int cmp(int g1, int g2, int[][] records, int n) {
		int max = Integer.MIN_VALUE;
		for (int i = 0; i < n; ++i) {
			max = Math.max(Math.max(max, records[i][0]), records[i][1]);
		}
		// 生成图的邻接表
		int[][] map = new int[max + 1][max + 1];
		// 检查是否遍历过,如果不加这个,会stackoverflow
		boolean[] visited = new boolean[max + 1];
		for (int i = 0; i < n; ++i) {
			map[records[i][0]][records[i][1]] = 1;
		}
        visited[g1] = true;
		dfs(g1, g2, map, visited);
        visited[g1] = false;
		if (flag)
			return 1;
        visited[g2] = true;
		dfs(g2, g1, map, visited);
        visited[g2] = false;
		if (flag)
			return -1;
		return 0;
	}

	private void dfs(int g1, int g2, int[][] map, boolean[] visited) {
		for (int i = 0; i < map[0].length; ++i) {
			if (map[g1][i] != 0) {// 说明有路径
				if (i == g2) {
					flag = true;
                    return;
				} else {
					if (!visited[i]) {
						visited[i] = true;
						dfs(i, g2, map, visited);
						visited[i] = false;
					}
				}
			}
		}
	}
}

编辑于 2017-08-23 18:22:26 回复(0)
class Cmp {
    set<int> d;
    vector<int> a;
    map<int,int> book;
public:
    int cmp(int g1, int g2, vector<vector<int> > r, int n) {
        // write code here
        int i,m1,m2,t1,t2,j;
        for(i=0;i<n;i++){ d.insert(r[i][0]);d.insert(r[i][1]); }
        set<int>::iterator it;
        for(it=d.begin();it!=d.end();it++) a.push_back(*it);
        for(i=0;i<a.size();i++){ book[a[i]]=i;if(a[i]==g1)m1=i;if(a[i]==g2)m2=i; }
        int N=a.size();
        vector<vector<int> > e(N,vector<int>(N,0));
        for(i=0;i<N;i++) for(j=0;j<N;j++) if(i-j) e[i][j]=99999; 
        for(i=0;i<n;i++) e[book[r[i][0]]][book[r[i][1]]]=1;
        t1=Dijkstra(e,m1,m2,N); t2=Dijkstra(e,m2,m1,N);
        if(t1<99999)return 1; else if(t2<99999) return -1;
        return 0;
    }
    int Dijkstra(vector<vector<int> > e,int x,int y,int n)
    {
        int i,j,u,Min,flag;
        vector<int> dis(n),book(n,0);
        book[x]=1;
        for(i=0;i<n;i++) dis[i]=e[x][i];
        for(i=0;i<n-1;i++)
        {
            flag=0;
            Min=99999;
            for(j=0;j<n;j++)
                if(book[j]==0&&Min>dis[j])
                {
                    Min=dis[j];
                    u=j;
                    flag=1;
                }
            if(flag==1)
            {
                book[u]=1;
                for(j=0;j<n;j++)
                    if(dis[j]>Min+e[u][j]) dis[j]=Min+e[u][j]; 
            }
        }
        return dis[y];
    }
};

发表于 2016-09-16 16:43:44 回复(0)
class Cmp {
public://论测试数据的重要性,还好小伙伴们及时发现。
    int cmp(int g1, int g2, vector<vector<int> > records, int n) {
		int i, j, x;
		for (i = 0; i < n; ++i)
		{
			if (records[i][0] == g1 && records[i][1] == g2)
				return 1;
			if (records[i][0] == g2 && records[i][1] == g1)
				return -1;
			if (records[i][0] == g1)
			{
				x = records[i][1];
				for (j = 0; j < n; ++j)
					if (records[j][0] == x && records[j][1] == g2)
						return 1;
			}
			if (records[i][0] == g2)
			{
				x = records[i][1];
				for (j = 0; j < n; ++j)
					if (records[j][0] == x && records[j][1] == g1)
						return -1;
			}
		}
		return 0;
    }
};

编辑于 2016-08-02 06:21:18 回复(11)

宽度优先搜索

构建有向图,方向规定为“轻钻石->重钻石”,以为起点进行BFS,如果经过了g_2g_2就是更重的钻石;以g_2为起点进行BFS,如果经过了就是更重的钻石。如果两次BFS都没能确定相对重量,那就无法判断。
import java.util.*;

public class Cmp {
    public int cmp(int g1, int g2, int[][] records, int n) {
        // 构建有向图,轻钻石指向重钻石
        HashMap<Integer, LinkedList<Integer>> graph = new HashMap<>();
        for(int[] edge: records){
            int heavy = edge[0], light = edge[1];
            if(graph.containsKey(light)){
                graph.get(light).add(heavy);
            }else{
                LinkedList<Integer> neighbors = new LinkedList<>();
                neighbors.add(heavy);
                graph.put(light, neighbors);
            }
        }
        boolean smaller = bfs(graph, g1, g2, new HashSet<Integer>());
        boolean bigger = bfs(graph, g2, g1, new HashSet<Integer>());
        if(smaller){
            return -1;
        }else if(bigger){
            return 1;
        }else{
            return 0;
        }
    }
    
    private boolean bfs(HashMap<Integer, LinkedList<Integer>> graph, int start, int end, HashSet<Integer> visited) {
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(start);
        while(!queue.isEmpty()){
            int cur = queue.poll();
            visited.add(cur);
            if(graph.containsKey(cur)){
                for(int next : graph.get(cur)){
                    if(visited.contains(next)){
                        continue;
                    }
                    if(next == end){
                        return true;
                    }else{
                        queue.offer(next);
                    }
                }
            }
        }
        return false;
    }
}

编辑于 2022-02-24 17:24:34 回复(0)
	public static int cmp(int g1, int g2, int[][] records, int n) {
		Graph graph = new Graph();
		//生成图
		for (int i = 0; i < records.length; i++) {
			graph.addEdge(records[i][0], records[i][1]);
		}
		// 看g1比g2重吗?
		int findNext1 = findNext(graph, g1, g2);
		// 看g2比g1重吗?
		int findNext2 = findNext(graph, g2, g1);
		if (findNext1 == 1)
			return 1;
		if (findNext2 == 1)
			return -1;
		// 如果都比不出来就无法比较
		return 0;
	}

	//该集合为判断是否有回路的集合.
	static HashMap<Integer, Integer> map = new HashMap<>();

	public static int findNext(Graph graph, int begin, int target) {
		ArrayList<Integer> values = graph.adj(begin);
		if (values == null || values.size() == 0)
			return 0;
		for (int i = 0; i < values.size(); i++) {
			int val = values.get(i);
			// 找到就不再向下找了.
			if (val == target)
				return 1;
			else {
				//在这里判断是不是有回路. 不回路就跳过.
				if (map.get(val) != null && (map.get(val) == 1 || map.get(val) == begin))
					continue;
				map.put(val, 1);
				int findNext = findNext(graph, val, target);
				// 找到就不再向下找了.
				if (findNext == 1)
					return 1;
			}
		}
		return 0;
	}

	static class Graph {
		//图的邻接表
		HashMap<Integer, ArrayList<Integer>> adjacent = new HashMap<Integer, ArrayList<Integer>>();

		//添加弧i->j
		public void addEdge(int i, int j) {
			if (adjacent.get(i) == null) {
				ArrayList<Integer> list = new ArrayList<>();
				adjacent.put(i, list);
			}
			adjacent.get(i).add(j);
		}

		//邻接集合
		public ArrayList<Integer> adj(int i) {
			return adjacent.get(i);
		}
	} 


你们的测试用例有问题啊!!!, 你看,先上来一个就是5,5 . 这是啥意思? 5比自己重???你们的题都设计不好,还提交个毛啊?
----------------所以......-----------------
需要测试是不是有回路.
--------------------------------

您的代码已保存
答案错误:您提交的程序没有通过所有的测试用例

case通过率为0.00%
测试用例:
12,2,[[5,5],[2,4],[8,6],[12,10],[12,12],[6,12],[2,3],[8,5],[7,5],[5,5],[3,10],[11,11],[12,12],[10,11],[7,3],[2,3],[11,5],[1,9],[8,12],[3,10],[8,4],[7,1],[9,5],[6,4],[1,11],[7,9],[12,12],[4,11],[8,6],[2,3],[12,5],[2,7],[4,11],[4,11],[3,3],[4,11],[3,4],[8,1],[10,9],[4,5],[6,9],[8,10],[7,11],[12,5],[2,12],[1,9],[7,3],[8,10],[2,1],[8,4],[3,11],[6,4],[2,4],[7,1],[6,6],[8,1],[1,4],[3,5],[12,10],[1,5],[2,4],[6,3],[7,12],[6,10],[6,11],[7,12],[7,4],[9,5],[2,11],[2,6],[6,5],[8,5],[1,9],[6,4],[7,1],[1,1],[2,9],[8,4],[6,5],[1,10],[6,3],[8,7],[8,2],[6,5],[2,12],[4,9],[7,11],[4,9],[2,10],[8,10],[12,10],[6,3],[2,10],[12,9],[8,4],[2,12],[7,11],[9,5],[3,5],[2,5],[7,9],[8,10],[7,9],[4,4],[2,3],[2,2],[7,3],[6,5],[2,4],[4,9],[8,10],[12,9],[2,9],[8,9],[12,5],[8,2],[3,12],[1,12],[1,12],[8,2],[2,5],[1,10],[12,5],[3,4],[8,11],[2,12],[8,2],[10,11],[8,3],[2,7],[8,6],[1,10],[7,12],[8,6],[1,1],[3,4]],136

对应输出应该为:

-1

你的输出为:

java.lang.IndexOutOfBoundsException: Index: 5, Size: 0



编辑于 2016-08-05 21:19:04 回复(1)
import java.util.*;

public class Cmp {
    public int cmp(int g1, int g2, int[][] records, int n) {
        ArrayList<Integer> bigger=new ArrayList<Integer>();//存储比g1大的元素
        ArrayList<Integer> smaller=new ArrayList<Integer>();//存储比g1小的元素 boolean flag=true;
        for(int i=0;i<n;i++){
            if(records[i][0]==g1){
                smaller.add(records[i][1]);//比g1小的集合
            }else if(records[i][1]==g1){
                bigger.add(records[i][0]);//比g1大的集合
            }
     	}
        while(flag){
            flag=false;
            for(int i=0;i<n;i++){
                for(int j=0;j<smaller.size();j++){
                    if(smaller.get(j)==records[i][0]){
                        smaller.add(records[i][1]);//更新比g1小的集合
                        records[i][0]=-1;//比较过后则废弃
                        flag=true;
                    }
                }
            }
        }
        flag=true;
        while(flag){
            flag=false;
            for(int i=0;i<n;i++){
                for(int j=0;j<bigger.size();j++){
                    if(bigger.get(j)==records[i][1]){
                        bigger.add(records[i][0]);//更新比g1大的集合
                        records[i][1]=-1;//比较过后则废弃
                        flag=true;
                    }
                }
            }
        }
        for(int i=0;i<smaller.size();i++){
            if(smaller.get(i)==g2){
                return 1;//如果g2在比g1小的集合中,则返回1
            }
        }
        for(int i=0;i<bigger.size();i++){
            if(bigger.get(i)==g2){
                return -1;//如果g2在比g1大的集合中,则返回-1
            }
        }
        return 0;//否则返回0
    }
}
发表于 2016-06-01 11:21:00 回复(0)
class Cmp {
public:
    int cmp(int g1, int g2, vector<vector<int> > records, int n) {
        // write code here
        const int Max = 10000000;
        const int Min = -1;
        set<int> g1_max, g1_min;
        set<int> g2_max, g2_min;
        for(int i=0;i<n;i++){
            int less = records[i][1];
            int more = records[i][0];
            if(more == g1 && less == g2){
                return 1;
            }
            else if(more == g2 && less == g1){
                return -1;
            }
            if(more == g1){
                g1_min.insert(less);
            }
            else if(less == g1){
                g1_max.insert(more);
            }
            if(more == g2){
                g2_min.insert(less);
            }
            else if(less == g2){
                g2_max.insert(more);
            }
        }
        set<int> intersection;
        set_intersection(g1_min.begin(), g1_min.end(), g2_max.begin(),g2_max.end(),inserter(intersection,intersection.begin()));
        if(!intersection.empty()){
            return 1;
        }
        set<int> intersection_2;
        set_intersection(g1_max.begin(), g1_max.end(), g2_min.begin(),g2_min.end(),inserter(intersection_2,intersection_2.begin()));
        if(!intersection_2.empty()){
            return -1;
        }
        return 0;
    }
};

发表于 2016-03-31 10:32:19 回复(0)
import java.util.*; public class Cmp {
//用于存放已经使用过的无效记录
    Vector<Integer> cmped = new Vector<>();     public int cmp(int g1, int g2, int[][] records, int n) {
// 采用递归的方法进行深度优先遍历
        if (left(g1, g2, records, n) == 1)             return 1;         else             return left(g2, g1, records, n) * (-1);     }     public int left( int g1, int g2, int[][] records, int n) {
//每次递归都遍历整个数组,但是遇到已经计算过的无效记录或者数据本身无效则跳过
        for (int i = 0; i < n; i++) {
        int[] record=records[i];         if (cmped.contains(i)||record[0] == record[1])         continue;         if (record[0] == g1 && record[1] != g2) {     cmped.add(i);     if( left( record[1], g2, records, n)==1)         return 1; } else if (record[0] == g1 && record[1] == g2) {     return 1;     } } return 0;     } }

编辑于 2016-04-05 19:08:32 回复(0)
import java.util.*;

public class Cmp {
    public int cmp(int g1, int g2, int[][] records, int n) {
        // write code here
        Map<Integer,List<Integer>> map = create_graph(records,n);
        if(helper(g1,g2,map))//g1重于g2
            return 1;
        else if(helper(g2,g1,map))//g1请g2
            return -1;
        return 0;//无法判断
    }
    public boolean helper(int g1,int g2,Map<Integer,List<Integer>> map){//广度优先遍历,判断是否路径点可达
        if (!map.containsKey(g1))//判断是否存在g1,不存在直接pass
            return false;
        Map<Integer,Integer> flag = new HashMap();//记录是否访问过该点
        Set<Integer> set = map.keySet();
        for (Integer i : set)
            flag.put(i, 0);
        Queue<Integer> queue = new LinkedList();
        queue.offer(g1);
        while(!queue.isEmpty()){
            List<Integer> temp = map.get(queue.poll());
            for(int i=0;i<temp.size();i++){
                if(flag.get(temp.get(i))==null)//不存在该点
                    continue;
                if(temp.get(i)==g2)//可达
                    return true;
                if(flag.get(temp.get(i))==0){
                    flag.replace(temp.get(i),1);
                    queue.offer(temp.get(i));
                }
            }
        }
        return false;
    }
    public Map<Integer,List<Integer>> create_graph(int[][] records,int n){//构建邻接表
        Map<Integer,List<Integer>> map = new HashMap();
        for(int i=0;i<n;i++){
            if(map.containsKey(records[i][0]))
                map.get(records[i][0]).add(records[i][1]);
            else{
                List<Integer> list = new ArrayList();
                list.add(records[i][1]);
                map.put(records[i][0],list);
            }
        }
        return map;
    }
}

发表于 2019-08-21 22:26:50 回复(0)
//用一个二维数组map[][]表示有向图的邻接矩阵,map[i] 代表着i与其他所有点的连通关系,如果i可以到j,则map[i][j] = j
//首先从g1出发去找g2,采用深度优先遍历,这里要尤其注意访问过的点一定要标记下来,不要多次访问,会导致栈溢出
//如果前一步没找到g2,那么从g2出发去找g1
//如果前两步都没成功,返回0
import java.util.*;

public class Cmp {
    boolean flag = false;
    public int cmp(int g1, int g2, int[][] records, int n) {
        // write code here
        int[][] map = new int[100][100];
        for(int[] arr : records){
            map[arr[0]][arr[1]] = arr[1];
        }
        search(g1,g2,map,new int[100]);
        if(flag) return 1;
        search(g2,g1,map,new int[100]);
        if(flag) return -1;
        return 0;
    }

    public void search(int g1, int g2, int[][]map,int[] visited){
        for(int i:map[g1]){
            if(flag) return;
            if(i == 0 || visited[i] == 1) continue;
            if(i == g2) {
                flag = true;
                return;
            }
            else {
                visited[i] = 1;
                search(i,g2,map,visited);
            }
        }
    }
}

                                                                                    
发表于 2018-05-09 21:39:15 回复(0)
//构建 图。 比 i节点 小的所有节点认为可达
//题目只要求 求g1>g2 或者 g2>g1 如果g2,g1可比较 则在g1深度遍历(g2深度遍历)时存在至少一条到达的路
//用flags数组 记录已经查询过的节点来截枝
class Cmp {
private:
     
public:
    int cmp(int g1, int g2, vector<vector<int> > records, int n) {
        int mai=0;
        for(int i=0;i<n;++i){
            for(int j=0;j<2;++j)
                if(records[i][j]>mai)
                    mai = records[i][j];
        }
        vector<vector<int> > dp(mai+1,vector<int>(mai+1,0));
        vector<bool> flags(mai+1,0);
        for(int i=0;i<n;++i){
            dp[records[i][0]][records[i][1]] = 1;
        }
        flags[g1] = true;
        if(dps(dp,flags,mai,g1,g2))
            return true;
        for(int i=0;i<=mai;++i)
            flags[i] = 0;
        flags[g2] = true;
        if(dps(dp,flags,mai,g2,g1))
            return -1;
        return 0;
    }
    bool dps(vector<vector<int> >& dp,vector<bool>& flags,int mai,int g1,int g2){
        if(dp[g1][g2])
            return true;
        flags[g1] = true;
        for(int i=1;i<=mai;++i){
            if(dp[g1][i] && !flags[i])
                if(dps(dp,flags,mai,i,g2))
                    return true;
        }
        return false;
    }
};
发表于 2018-05-07 07:52:47 回复(0)
可以使用集合,不过集合的构造需要两步
importjava.util.*;
importjava.util.HashMap;
importjava.util.HashSet;
publicclassCmp {
    publicintcmp(intg1, intg2, int[][] records, intn) {
        // write code here
         HashMap<Integer,HashSet<Integer>> hashMap=newHashMap<>();
        for(inti=0;i<records.length;++i)
        {
            if(hashMap.containsKey(records[i][0])==false)
            {
                HashSet<Integer> hashSet=newHashSet<>();
                hashSet.add(records[i][1]);
                if(hashMap.containsKey(records[i][1]))
                    hashSet.addAll(hashMap.get(records[i][1]));
                hashMap.put(records[i][0],hashSet);
            }
            else
            {
                HashSet<Integer> hashSet=hashMap.get(records[i][0]);
                hashSet.add(records[i][1]);
                if(hashMap.containsKey(records[i][1]))
                    hashSet.addAll(hashMap.get(records[i][1]));
                hashMap.put(records[i][0],hashSet);
            }
        }
 
 
        for(inti=0;i<records.length;++i)
        {
            if(hashMap.containsKey(records[i][0])==false)
            {
                HashSet<Integer> hashSet=newHashSet<>();
                hashSet.add(records[i][1]);
                if(hashMap.containsKey(records[i][1]))
                    hashSet.addAll(hashMap.get(records[i][1]));
                hashMap.put(records[i][0],hashSet);
            }
            else
            {
                HashSet<Integer> hashSet=hashMap.get(records[i][0]);
                hashSet.add(records[i][1]);
                if(hashMap.containsKey(records[i][1]))
                    hashSet.addAll(hashMap.get(records[i][1]));
                hashMap.put(records[i][0],hashSet);
            }
        }
 
 
 
        if(hashMap.containsKey(g1)==false&&hashMap.containsKey(g2)==false)
            return0;
         if(hashMap.containsKey(g1))
        {
            HashSet<Integer> data=hashMap.get(g1);
            if(data.contains(g2))
                return1;
        }if(hashMap.containsKey(g2))
        {
            HashSet<Integer> data=hashMap.get(g2);
            if(data.contains(g1))
                return-1;
        }
        return0;
    }
}

发表于 2018-03-26 21:20:58 回复(0)
//抄的答案,答主的答案很不错
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Main{
    
    public static boolean reachable = false;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int g1 = 2;
        int g2 = 3;
        int [][] records = new int [4][2];
        int n = 4;
        records[0][0] = 1;
        records[0][1] = 2;    //(1,2)
        records[1][0] = 2;
        records[1][1] = 4;    //(2,4)
        records[2][0] = 1;
        records[2][1] = 3;    //(1,3)
        records[3][0] = 4;
        records[3][1] = 3;    //(4,3)
        System.out.println(cmp(g1,g2,records,n));
    }
    
    public static int cmp(int g1, int g2, int[][] records, int n) {
        // write code here
        HashMap<Integer, List<Integer>> map = generateMap(records,n);
        
        if(map.isEmpty()){
            return 0;
        }
        
        depthSearch(g1,g2,map);
        if(reachable == true){
            return 1;
        }
        
        reachable = false;
        depthSearch(g2,g1,map);
        if(reachable == true){
            return -1;
        }
        
        return 0;
    }
    
    public static void depthSearch(int g1,int g2,HashMap<Integer, List<Integer>> map){
        if(!map.containsKey(g1)){
            reachable = false;
        }
        else {
            List<Integer> values = map.get(g1);
            for(int value : values){
                if(g2 == value){
                    reachable = true;
                    return;
                }
                else {
                    depthSearch(value, g2, map);    //重点
                }
            }
        }
    }
    
    public static HashMap<Integer, List<Integer>> generateMap(int [][] records,int n){
        HashMap<Integer, List<Integer>> map = new HashMap<>();
        for(int i = 0;i < n;i++){
            int key = records[i][0];
            int value = records[i][1];
            if(map.containsKey(key)){
                map.get(key).add(value);
            }
            else {
                List<Integer> list = new ArrayList<>();
                list.add(value);
                map.put(key, list);
            }
        }
        return map;
    }

}


发表于 2018-01-10 17:01:33 回复(0)
#include <unordered_map>
#include <unordered_set>

class Cmp {
public:
    bool BFS(const unordered_multimap<int,int>& Graph,
             int s,int d)
    {        
        unordered_set<int> blackFlag;// 访问标记

        queue<int> que;
        que.push(s);
        blackFlag.insert(s);//标记为已遍历

        // 广度优先遍历
        while(!que.empty())
         {
            int cur = que.front();
            que.pop();
            if(cur == d) // 找到
                return true;

            auto pairIt = Graph.equal_range(cur);
            for(auto it =pairIt.first;it!=pairIt.second;it++)
                {
                if(blackFlag.find(it->second)!=blackFlag.end())
                    continue; // 遍历过的节点
                que.push(it->second);
                blackFlag.insert(it->second);//标记为已遍历
            }
        }

        return false;
    }

    // 很明显,钻石之间的重量关系是一个有向无环图
    int cmp(int g1, int g2, vector<vector<int> > records, int n) {
        // write code here
        unordered_multimap<int,int> Graph;
        for(vector<int>&a:records)
            Graph.insert(make_pair(a[0],a[1]));

        if(BFS(Graph,g1,g2))
            return 1;
        if(BFS(Graph,g2,g1))
            return -1;

        return 0;    
    }
};
编辑于 2017-06-03 23:44:33 回复(0)
classCmp {
public:
    intcmp(intg1,intg2, vector<vector<int> > records,intn) {
        intleft,right;
        intsize=n;
        for(inti=0;i<size;++i){
            for(intj=0;j<size;++j){
                if(records[i][1]==records[j][0]){
                    left=records[i][0];
                    right=records[j][1];
                    vector<int> tmp;
                    tmp.push_back(left);
                    tmp.push_back(right);
                    records.push_back(tmp);
                }
            }
        }
        size=records.size();
        for(inti=0;i<size;++i){
            if(records[i][0]==g1){
                if(records[i][1]==g2)
                    return1;
            }
            if(records[i][0]==g2){
                if(records[i][1]==g1)
                    return-1;
            }
        }
        return0;
    }
};

发表于 2017-03-22 16:45:16 回复(0)

哪位大神帮忙看一下哪里错了?老是报越界

public static int cmp(int g1, int g2, int[][] records, int n) {
        Map<Integer, Set<Integer>> map = new HashMap<>();

        for(int[] x : records) {
            if(map.containsKey(x[0])) {
                map.get(x[0]).add(x[1]);
            } else {
                map.put(x[0], new HashSet<Integer>());
                map.get(x[0]).add(x[1]);
            }
        }

        if(helper(map, g1, g2)) return 1;
        else if(helper(map, g2, g1)) return -1;
        else return 0;
    }

    private static boolean helper(Map<Integer, Set<Integer>> map, int x, int y) {
        if(!map.containsKey(x)) return false;
        Set<Integer> set = map.get(x);
        if(set.contains(y)) return true;

        for(int i : set) {
            if(helper(map, i, y)) return true;
        }

        return false;
    }
发表于 2017-02-26 22:25:14 回复(0)