这是我ACM进程的第一题,发布上来一是为了督促自己,二是希望看到的大神可以指点错误,三是给自己的acm留个印记
废话不多说,直接代码:
package demon;
/*
* 题目大意: 在一个一维牧场有N头牛对应着N个位置,每头牛都对其余的牛“哞”,音量即为两者的距离。
* 求牛对其他牛的叫声音量的之和
* 对于这条问题解答其实不需要知道每个牛的location。但是如果还要给出每一个牛对应的音量和的话,就得需要lcation。
*/
public class P2231 {
static int N = 0 ;
public static void main(String[] args) {
N = 5;
int[] location = {1,5,3,2,4};
//第一个方法
System.out.println(getTotle1(5));
//第二个方法
System.out.println(getTotle2(5,location));
}
//这个是不需要location的方法
public static int getTotle1(int N) {
int totle = 0;
for (int i = 1; i <= N; i ++) {
for (int j = 1; j <=N; j ++) {
totle += Math.abs(i - j);
}
}
return totle;
}
//这个是需要location的方法
public static int getTotle2(int N, int[] a) {
int totle = 0;
for (int i = 0; i < a.length; i ++) {
for (int j = 1; j <=N; j ++) {
totle += Math.abs(a[i] - j);
}
System.out.println("第" + a[i] + "头牛本身和它之前的牛所需要的总音量" + totle );
}
return totle;
}
}
废话不多说,直接代码:
package demon;
/*
* 题目大意: 在一个一维牧场有N头牛对应着N个位置,每头牛都对其余的牛“哞”,音量即为两者的距离。
* 求牛对其他牛的叫声音量的之和
* 对于这条问题解答其实不需要知道每个牛的location。但是如果还要给出每一个牛对应的音量和的话,就得需要lcation。
*/
public class P2231 {
static int N = 0 ;
public static void main(String[] args) {
N = 5;
int[] location = {1,5,3,2,4};
//第一个方法
System.out.println(getTotle1(5));
//第二个方法
System.out.println(getTotle2(5,location));
}
//这个是不需要location的方法
public static int getTotle1(int N) {
int totle = 0;
for (int i = 1; i <= N; i ++) {
for (int j = 1; j <=N; j ++) {
totle += Math.abs(i - j);
}
}
return totle;
}
//这个是需要location的方法
public static int getTotle2(int N, int[] a) {
int totle = 0;
for (int i = 0; i < a.length; i ++) {
for (int j = 1; j <=N; j ++) {
totle += Math.abs(a[i] - j);
}
System.out.println("第" + a[i] + "头牛本身和它之前的牛所需要的总音量" + totle );
}
return totle;
}
}
分享了ACM进程中的第一道题目,并提供了两种解决方法。一种方法不需要位置信息,另一种则需要。通过代码实现来求解牛对其他牛叫声音量的总和。

320

被折叠的 条评论
为什么被折叠?



