zoukankan      html  css  js  c++  java
  • P1967 货车运输 -60分

    打了一个最大生成树+dfs,60分成功tle

    #include <bits/stdc++.h>
    using namespace std;
    const int maxn = 10005;
    const int maxm = 50005;
    int n, m, cnt = 0;
    struct edge
    {
    	int from, to, value;
    	bool operator < (const edge b) const {
    		return this->value > b.value;
    	}
    }es[maxm];
    vector<edge> G[maxn];
    struct car
    {
    	int from, to;
    }cs[30001];
    int q;
    void read() {
    	cin >> n >> m;
    	for(int i = 1; i <= m; i++) {
    		int x, y, z;
    		cin >> x >> y >> z;
    		es[cnt].from = x;
    		es[cnt].to = y;
    		es[cnt].value = z;
    		cnt++; 
    	}
    	cin >> q;
    	for(int i = 1; i <= q; i++) cin >> cs[i].from >> cs[i].to;
    }
    int fa[maxn];
    int find(int x) {
    	return x == fa[x] ? x : fa[x] = find(fa[x]);
    }
    void kruskal() {
    	sort(es, es+cnt);
    	for(int i = 1; i <= n; i++) fa[i] = i;
    	for(int i = 0; i < cnt; i++) {
    		int x = es[i].from; int y = es[i].to;
    		int fx = find(x); int fy = find(y);
    		if(fx == fy) {
    			es[i].value = -1;
    			continue;
    		}
    		else fa[fx] = fy;
    	}
    }
    void build_tree() {
    	sort(es, es+cnt);
    	for(int i = 0; i < cnt; i++) {
    		if(es[i].value != -1) {
    			int x = es[i].from;
    			int y = es[i].to;
    			G[x].push_back({x, y, es[i].value});
    			G[y].push_back({y, x, es[i].value});
    		}
    		else break;
    	}
    }
    int mini = 0x3f3f3f;
    int vis[maxn];
    void dfs(int from, int to, int m) {
    	vis[from] = 1;
    	if(from == to) {mini = m; return;}
    	vector<edge>::iterator it;
    	for(it = G[from].begin(); it != G[from].end(); it++) {
    		edge &e = *it;
    		if(!vis[e.to]) {
    			dfs(e.to, to, min(m, e.value));
    		}
    	}
    }
    void solve() {
    	for(int i = 1; i <= q; i++) {
    		int x = cs[i].from;
    		int y = cs[i].to;
    		mini = 0x3f3f3f;
    		memset(vis, 0, sizeof(vis));
    		dfs(x, y, 0x3f3f3f);
    		if(mini == 0x3f3f3f) cout << -1;
    		else cout << mini;
    		cout << endl;
    	}
    }
    int main() {
    //	freopen("input.in", "r", stdin);
    	read();
    	kruskal();
    	build_tree();
    	solve();
    	return 0;
    }
    
  • 相关阅读:
    【hibernate】自定义转换器
    【hibernate】存储图片
    【hibernate】映射可嵌入式组件
    【hibernate】应用程序级别的视图
    adb shell模拟点击事件(input tap)
    Android UIAutomator 定位
    adb devices连接不上设备
    获取元素属性get_attribute
    wait_activity
    webview定位 & native和webview切换
  • 原文地址:https://www.cnblogs.com/gengchen/p/6066022.html
Copyright © 2011-2022 走看看