2016-2017 ACM-ICPC, NEERC, Moscow Subregional Contest K Knights of the Old Republic(贪心+DP)

传送门:戳这里

将边按从小到大排序,模拟Kruskal,设当前要合并的2个集合为x和y
设要占领当前这条边,需要花费w
①如果要占领这条边,则花费为min(b[v]) * max(w, max(a[u])),其中u和v是集合x和y中的点
②如果不占领这条边,则花费为f[x] + f[y]

#include
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define x first
#define y second
#define rep(i,a,b) for(int i=(a);i<(b);++i)
#define per(i,a,b) for(int i=(a)-1;i>=(b);--i)
#define fuck(x) cout<<'['<<#x<<' '<<(x)<<']'< VI;
typedef pair pii;
typedef unsigned int ui;
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
const int MX = 3e5 + 5;
struct Edge {
    int u, v, w;
    bool operator<(const Edge& _A) const {
        return w < _A.w;
    }
} E[MX];
ll f[MX];
int p[MX], a[MX], b[MX];
int find(int x) {return p[x] == x ? x : (p[x] = find(p[x]));}

ll solve(int n, int m) {
    sort(E + 1, E + m + 1);
    rep(i, 1, m + 1) {
        int u = E[i].u, v = E[i].v, w = E[i].w;
        int x = find(u), y = find(v);
        if(x == y) continue;
        int ta = max(w, max(a[x], a[y]));
        int tb = min(b[x], b[y]);
        f[x] = min(f[x] + f[y], (ll) ta * tb);
        p[y] = x;
        a[x] = max(a[x], a[y]);
        b[x] = min(b[x], b[y]);
    }
    ll ans = 0;
    rep(i, 1, n + 1) if(find(i) == i) ans += f[i];
    return ans;
}
int main() {
#ifdef local
    freopen("in.txt", "r", stdin);
#endif // local
    int n, m; cin >> n >> m;
    rep(i, 1, n + 1) scanf("%d%d", &a[i], &b[i]);
    rep(i, 1, m + 1) scanf("%d%d%d", &E[i].u, &E[i].v, &E[i].w);
    rep(i, 1, n + 1) p[i] = i, f[i] = (ll) a[i] * b[i];
    printf("%lld\n", solve(n, m));
    return 0;
}

 

你可能感兴趣的:(DP,贪心)