1. 程式人生 > >洛谷 P1577 切繩子 題解

洛谷 P1577 切繩子 題解

scanf ac代碼 兩個 精度 clas c2c amp str 整數

此文為博主原創題解,轉載時請通知博主,並把原文鏈接放在正文醒目位置。

題目鏈接:

題目描述

有N條繩子,它們的長度分別為Li。如果從它們中切割出K條長度相同的

繩子,這K條繩子每條最長能有多長?答案保留到小數點後2位。

輸入輸出格式

輸入格式:

第一行兩個整數N和K,接下來N行,描述了每條繩子的長度Li。

輸出格式:

切割後每條繩子的最大長度。

輸入輸出樣例

輸入樣例#1:
4 11
8.02
7.43
4.57
5.39
輸出樣例#1:
2.00

說明

對於100%的數據 0<Li<=100000.00 0<n<=10000 0<k<=10000

分析:

一開始沒想到什麽好辦法,精度0.001直接二分,精彩地WA了7個點...

之後又把精度加到0.0001,並沒啥用

然後發現“好像二分計算整數更合適吧”

emmmmmm....

47分代碼:

技術分享
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<algorithm> 
 6 
 7 const int MAXN = 10005;
 8 
 9
inline void read(int &x) 10 { 11 x = 0;char ch = getchar(), c = ch; 12 while(ch < 0 || ch > 9)c = ch, ch = getchar(); 13 while(ch <= 9 && ch >= 0)x = x * 10 + ch - 0, ch = getchar(); 14 if(c == -)x = -x; 15 } 16 17 int n,k; 18 double l,r,mid,ans,num[MAXN],tmp[MAXN];
19 20 int cmp(int a,int b) 21 {return a>b;} 22 23 void update() 24 { 25 for(int i = 1;i <= n;++ i) 26 tmp[i] = num[i]; 27 } 28 29 bool jud(double x) 30 { 31 int tot = 0; 32 update(); 33 for(int i = 1;i <= n;++ i) 34 { 35 if(tot >= k) return true; 36 while(tmp[i]-x >=0) tot ++,tmp[i]-=x; 37 } 38 if(tot >= k) return true; 39 return false; 40 } 41 42 int main() 43 { 44 read(n),read(k); 45 for(int i = 1;i <= n;++ i) 46 scanf("%lf",&num[i]); 47 std::sort(num+1,num+1+n,cmp); 48 l = 0,r = num[n]; 49 while(l <= r) 50 { 51 mid = (l+r)/2.0; 52 if(jud(mid)) ans = mid,l = mid+0.0001; 53 else r = mid-0.0001; 54 } 55 printf("%.2lf",ans); 56 return 0; 57 }
1.6.9.10.11.12.AC

AC代碼:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm> 

const int MAXN = 10005;

inline void read(long long &x)
{
    x = 0;char ch = getchar(), c = ch;
    while(ch < 0 || ch > 9)c = ch, ch = getchar();
    while(ch <= 9 && ch >= 0)x = x * 10 + ch - 0, ch = getchar();
    if(c == -)x = -x;
}

long long n,k,l,r,mid,ans,num[MAXN],tmp[MAXN];
double a;

int cmp(long long a,long long b)
{return a>b;}

void update()
{
    for(int i = 1;i <= n;++ i)
        tmp[i] = num[i];
}

bool jud(long long x)
{
    int tot = 0;
    update();
    for(int i = 1;i <= n;++ i)
    {
        if(tot >= k) return true;
        if(num[i] < x || !x) break;
        tot += num[i]/x;
    }
    if(tot >= k) return true;
    return false;
}

int main()
{
    read(n),read(k);
    for(int i = 1;i <= n;++ i)
        scanf("%lf",&a),num[i] = a*100;
    std::sort(num+1,num+1+n,cmp);
    l = 0,r = num[1];
    while(l <= r)
    {
        mid = (l+r)>>1;
        if(jud(mid)) ans = mid,l = mid+1;
        else r = mid-1;
    }
    printf("%.2lf",(double)ans/100.0);
    return 0;
}

洛谷 P1577 切繩子 題解