hdu1281(二分图匹配)JAVA

为什么WA?


import java.io.IOException;
import java.util.Scanner;
import java.util.Vector;

class Main{
    
    
	
	static Vector<Integer> G[]=new Vector[500];
	static boolean used[]=new boolean[500];
	static int match[]=new int[500],V,match2[]=new int[500],n,m;
	static void add_edge(int u,int v) {
    
    
		G[u].add(v);
		G[v].add(u);
	}
/*	static boolean pdfs(int v) {

		for(int i=0;i<G[v].size();i++) {
			int u=G[v].get(i),w=match[u];
			if(w<0||!used[w]&&dfs(w)) {
				match[v]=u;
				match[u]=v;
				return true;
			}
		}
		return false;
	}*/
	static boolean dfs(int u) {
    
    
		for(int i=0;i<G[u].size();i++) {
    
    
			int v=G[u].get(i);
			if(!used[v]) {
    
    //要求不在交替路中
				used[v]=true;//放入交替路
				if(match[v]==-1||dfs(match[v])) {
    
    
					//是未覆盖点,说明交替路为增广路,交换路径并返回true
					match[v]=u;
					match[u]=v;
					return true;
				}
				used[v]=false;
			}
		}
		return false;
	}
	/*static int bi_matching() {
		int res = 0;
		for(int i=0;i<210;i++) {
			match[i]=-1;
		}
		for(int v = 0;v<V+1;v++) {	
			if(match[v]<0) {
				for(int i=0;i<210;i++) {
					used[i]=false;
				}
				if(dfs(v)) {
					res++;
				}
			}
		}
		return res;
	}*/
	static int hungarian() {
    
    
		int ans=0;
		for(int i=1;i<=n+m;i++) {
    
    
			match[i]=-1;
		}
		for(int i=1;i<=n;i++) {
    
    
			if(match[i]==-1) {
    
    
				for(int j=1;j<=n+m;j++) {
    
    
					used[j]=false;
				}
				if(dfs(i)) {
    
    
					ans++;
				}
			}
		}
		return ans;
	}
	
	public static void main(String args[]) throws IOException {
    
    		
		Scanner sc=new Scanner(System.in);			
		while(true) {
    
    
			n=sc.nextInt();
			m=sc.nextInt();
			int k=sc.nextInt();	
			int t=0;
			t++;
			V=n+m;
			for(int i=1;i<=V;i++) {
    
    
				G[i]=new Vector();
			}

			int a,b;
			for(int i=0;i<k;i++) {
    
    
				a=sc.nextInt();
				b=sc.nextInt();
				b+=n;
				add_edge(a, b);
			}
			int ans=0;
			int st = hungarian();
			for(int i=1;i<=V;i++) {
    
    
				match2[i]=match[i];
			}
			for(int i=1;i<=n;i++) {
    
    
				if(match2[i]!=-1) {
    
    
					 int u=i,v=match2[i];
					 //System.out.println(u+" "+v);
					 G[u].removeElement(v);
					 G[v].removeElement(u);
					 int st0=hungarian();
					 
					 if(st0<st)ans++;
					 add_edge(u, v);
					 
				}
			}
			System.out.println("Board "+t+" have "+ans+" important blanks for "+st+" chessmen. ");

		}
				
	}


}



猜你喜欢

转载自blog.csdn.net/qq_42021845/article/details/119185833