2018计蒜之道第一场A,B,C

A题 百度无人车

二分车的重量,最后特判一下结果是否为0,如果为0那么答案就是1。

AC代码:

#include 
using namespace std;
const int maxn = 2e4 + 7;
long long a[maxn];
int n;
long long s,p;
long long check(long long x){
    long long ans=0;
    int pos = lower_bound(a+1,a+1+n,x)-a;
    for(int i=pos;i<=n;i++){
        ans += (a[i]-x)*p;
    }
    return ans;
}
int main(){
    cin >> n;
    long long Max = 0;
    for(int i=1;i<=n;i++){
        cin >> a[i];
        Max = max(Max, a[i]);
    }
    cin >> p >> s;
    sort(a+1,a+1+n);
    long long l=0,r=Max+1;
    while(l<=r){
        long long mid=(l+r)>>1;
        if(check(mid)>s) l=mid+1;
        else r=mid-1;
    }
    if(l==0) cout << 1 << endl;
    else cout << l << endl;
    return 0;
}

C题 百度科学家(中等)

C题是B的加强版,这里就只发C的代码了,把题中的限制条件建边,跑tarjan求出强连通分量,对于出度为0的强连通分量求出最小的花费就行。

AC代码:

#include 
using namespace std;
const int maxn = 2e5 + 7;
const long long INF = 1e18;
int n,m;
typedef long long ll;
ll a[maxn];
vector  v[maxn];
int tot,idx,low[maxn],dfn[maxn],belong[maxn],sccnum;
int num[maxn];
int out[maxn];
bool vis[maxn];
ll cost[maxn];
stack  s;
void tarjan(int u){
    low[u] = dfn[u] = ++idx;
    vis[u] = true;
    s.push(u);
    for(int i=0;i<(int)v[u].size();i++){
        int V = v[u][i];
        if(!dfn[V]){
            tarjan(V);
            low[u] = min(low[u],low[V]);
        }else if(vis[V]){
            low[u] = min(low[u],dfn[V]);
        }
    }
    if(low[u] == dfn[u]){
        sccnum++;
        while(!s.empty()){
            int now = s.top();
            s.pop();
            vis[now] = false;
            cost[sccnum] += a[now];
            belong[now] = sccnum;
            if(now == u) break;
        }
    }
}
int main(){
    cin >> n;
    for(int i=1;i<=n;i++) cin >> a[i],num[i]=i;
    cin >> m;
    tot = n;
    for(int i=1;i<=m;i++){
        int op;
        cin >> op;
        if(op){
            int x,l,r;
            cin >> x >> l >> r;
            for(int j=l;j<=r;j++){
                v[num[x]].push_back(num[j]);
            }
        }else{
            int x;
            ll val;
            cin >> x >> val;
            a[++tot] = val;
            num[x] = tot;
        }
    }
    for(int i=1;i<=tot;i++){
        if(!dfn[i]){
            tarjan(i);
        }
    }
    for(int i=1;i<=tot;i++){
        for(int j=0;j<(int)v[i].size();j++){
            int to = v[i][j];
            if(belong[i] != belong[to]){
                out[belong[i]]++;
            }
        }
    }
    ll ans = INF;
    for(int i=1;i<=sccnum;i++){
        if(out[i] == 0){
            ans = min(ans,cost[i]);
        }
    }
    cout << ans << endl;
    return 0;
}

你可能感兴趣的:(图论,二分)